package org.kodejava.example.util;
import java.util.Hashtable;
import java.util.Random;
public class HashtableGetRandom {
public static void main(String[] args) {
// Create a hashtable and put some key-value pair.
Hashtable<String, String> colors = new Hashtable<>();
colors.put("black", "#000");
colors.put("red", "#f00");
colors.put("green", "#0f0");
colors.put("blue", "#00f");
colors.put("white", "#fff");
// Get a random entry from the hashtable.
String[] keys = colors.keySet().toArray(new String[colors.size()]);
String key = keys[new Random().nextInt(keys.length)];
System.out.println(key + " = " + colors.get(key));
}
}
Category Archives: Java
How to monitor file or directory changes?
package org.kodejava.io;
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
public class FileWatchDemo {
public static void main(String[] args) {
try {
// Creates a instance of WatchService.
WatchService watcher = FileSystems.getDefault().newWatchService();
// Registers the logDir below with a watch service.
Path logDir = Paths.get("F:/Temp/");
logDir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
// Monitor the logDir at listen for change notification.
while (true) {
WatchKey key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (ENTRY_CREATE.equals(kind)) {
System.out.println("Entry was created on log dir.");
} else if (ENTRY_MODIFY.equals(kind)) {
System.out.println("Entry was modified on log dir.");
} else if (ENTRY_DELETE.equals(kind)) {
System.out.println("Entry was deleted from log dir.");
}
}
key.reset();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
To get the created, modified or deleted file you can see the following example: How to get the file name when using WatchService?.
How to get the file name when using WatchService?
package org.kodejava.io;
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
public class WatchServiceGetFilename {
public static void main(String[] args) {
try {
// Create a WatchService and register the logDir path with the
// WatchService for ENTRY_CREATE.
WatchService watcher = FileSystems.getDefault().newWatchService();
Path logDir = Paths.get("F:/Temp");
logDir.register(watcher, ENTRY_CREATE);
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException e) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == ENTRY_CREATE) {
// Get the name of created file.
WatchEvent<Path> ev = cast(event);
Path filename = ev.context();
System.out.printf("A new file %s was created.%n",
filename.getFileName());
}
}
key.reset();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>) event;
}
}
How to write file using Files.newBufferedWriter?
To open a file for writing in JDK 7 you can use the Files.newBufferedWriter() method. This method takes three arguments. We need to pass the Path, the Charset and a varargs of OpenOption.
For example, in the snippet below we pass the path of our log file, we use the StandardCharsets.UTF_8 charset, and we use the StandardOpenOption.WRITE to open a file for writing. If you want to open a file and append its contents instead of rewriting it you can use the StandardOpenOption.APPEND.
package org.kodejava.io;
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FilesNewBufferedWriter {
public static void main(String[] args) throws Exception {
Path logFile = Paths.get("app.log");
if (Files.notExists(logFile)) {
Files.createFile(logFile);
}
try (BufferedWriter writer =
Files.newBufferedWriter(logFile, StandardCharsets.UTF_8,
StandardOpenOption.WRITE)) {
for (int i = 0; i < 10; i++) {
writer.write(String.format("Message %s%n", i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Because we use the StandardOpenOption.WRITE we have to make sure that the file to be written is exists. If the file is not available we will get error like java.nio.file.NoSuchFileException.
How to read file using Files.newBufferedReader?
In the snippet below you’ll learn to open file for reading using Files.newBufferedReader() method in JDK 7. This method returns a java.io.BufferedReader which makes a backward compatibility with the old I/O system in Java.
To read a file you’ll need to provide a Path and the Charset to the newBufferedReader() method arguments.
package org.kodejava.io;
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FilesNewBufferedReader {
public static void main(String[] args) {
Path logFile = Paths.get("app.log");
try (BufferedReader reader =
Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
