Skip to content

Commit 098db62

Browse files
Merge branch 'master' into pr/858-tim
2 parents aecc850 + 753c71a commit 098db62

63 files changed

Lines changed: 2138 additions & 1132 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.baeldung.java.nio2.visitor;
2+
3+
import static java.nio.file.FileVisitResult.CONTINUE;
4+
import static java.nio.file.FileVisitResult.TERMINATE;
5+
6+
import java.io.IOException;
7+
import java.nio.file.FileVisitResult;
8+
import java.nio.file.FileVisitor;
9+
import java.nio.file.Files;
10+
import java.nio.file.Path;
11+
import java.nio.file.Paths;
12+
import java.nio.file.attribute.BasicFileAttributes;
13+
14+
public class FileSearchExample implements FileVisitor<Path> {
15+
private static String FILE_NAME;
16+
private static Path START_DIR;
17+
18+
public FileSearchExample(String fileName, Path startingDir) {
19+
FILE_NAME = fileName;
20+
START_DIR = startingDir;
21+
}
22+
23+
@Override
24+
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
25+
return CONTINUE;
26+
}
27+
28+
@Override
29+
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
30+
String fileName = file.getFileName().toString();
31+
if (FILE_NAME.equals(fileName)) {
32+
System.out.println("File found: " + file.toString());
33+
return TERMINATE;
34+
}
35+
return CONTINUE;
36+
}
37+
38+
@Override
39+
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
40+
System.out.println("Failed to access file: " + file.toString());
41+
return CONTINUE;
42+
}
43+
44+
@Override
45+
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
46+
boolean finishedSearch = Files.isSameFile(dir, START_DIR);
47+
if (finishedSearch) {
48+
System.out.println("File:" + FILE_NAME + " not found");
49+
return TERMINATE;
50+
}
51+
return CONTINUE;
52+
}
53+
54+
public static void main(String[] args) throws IOException {
55+
Path startingDir = Paths.get("C:/Users/new/Desktop");
56+
FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir);
57+
Files.walkFileTree(startingDir, crawler);
58+
}
59+
60+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.java.nio2.visitor;
2+
3+
import java.io.IOException;
4+
import java.nio.file.FileVisitResult;
5+
import java.nio.file.FileVisitor;
6+
import java.nio.file.Path;
7+
import java.nio.file.attribute.BasicFileAttributes;
8+
9+
public class FileVisitorImpl implements FileVisitor<Path> {
10+
11+
@Override
12+
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
13+
return null;
14+
}
15+
16+
@Override
17+
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
18+
return null;
19+
}
20+
21+
@Override
22+
public FileVisitResult visitFileFailed(Path file, IOException exc) {
23+
return null;
24+
}
25+
26+
@Override
27+
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
28+
return null;
29+
}
30+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.java.nio2.watcher;
2+
3+
import java.io.IOException;
4+
import java.nio.file.FileSystems;
5+
import java.nio.file.Path;
6+
import java.nio.file.Paths;
7+
import java.nio.file.StandardWatchEventKinds;
8+
import java.nio.file.WatchEvent;
9+
import java.nio.file.WatchKey;
10+
import java.nio.file.WatchService;
11+
12+
public class DirectoryWatcherExample {
13+
public static void main(String[] args) throws IOException, InterruptedException {
14+
WatchService watchService = FileSystems.getDefault().newWatchService();
15+
Path path = Paths.get(System.getProperty("user.home"));
16+
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
17+
WatchKey key;
18+
while ((key = watchService.take()) != null) {
19+
for (WatchEvent<?> event : key.pollEvents()) {
20+
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
21+
}
22+
key.reset();
23+
}
24+
}
25+
}

‎core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
package com.baeldung.file;
22

3-
import java.io.BufferedReader;
4-
import java.io.File;
5-
import java.io.FileInputStream;
6-
import java.io.IOException;
7-
import java.io.InputStream;
8-
import java.io.InputStreamReader;
3+
import org.apache.commons.io.FileUtils;
4+
import org.hamcrest.CoreMatchers;
5+
import org.hamcrest.Matchers;
6+
import org.junit.Assert;
7+
import org.junit.Test;
8+
9+
import java.io.*;
910
import java.net.URISyntaxException;
1011
import java.net.URL;
1112
import java.net.URLConnection;
@@ -14,12 +15,6 @@
1415
import java.nio.file.Paths;
1516
import java.util.stream.Stream;
1617

17-
import org.apache.commons.io.FileUtils;
18-
import org.hamcrest.CoreMatchers;
19-
import org.hamcrest.Matchers;
20-
import org.junit.Assert;
21-
import org.junit.Test;
22-
2318
public class FileOperationsUnitTest {
2419

2520
@Test
@@ -58,9 +53,9 @@ public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
5853

5954
@Test
6055
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
61-
String expectedData = "Baeldung";
56+
String expectedData = "Example Domain";
6257

63-
URL urlObject = new URL("http://www.baeldung.com/");
58+
URL urlObject = new URL("http://www.example.com/");
6459

6560
URLConnection urlConnection = urlObject.openConnection();
6661

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package com.baeldung.java.nio2.async;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.net.InetSocketAddress;
7+
import java.nio.ByteBuffer;
8+
import java.nio.channels.AsynchronousSocketChannel;
9+
import java.util.concurrent.ExecutionException;
10+
import java.util.concurrent.Future;
11+
12+
public class AsyncEchoClient {
13+
private AsynchronousSocketChannel client;
14+
private Future<Void> future;
15+
private static AsyncEchoClient instance;
16+
17+
private AsyncEchoClient() {
18+
try {
19+
client = AsynchronousSocketChannel.open();
20+
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
21+
future = client.connect(hostAddress);
22+
start();
23+
24+
} catch (IOException e) {
25+
e.printStackTrace();
26+
}
27+
}
28+
29+
public static AsyncEchoClient getInstance() {
30+
if (instance == null)
31+
instance = new AsyncEchoClient();
32+
return instance;
33+
}
34+
35+
private void start() {
36+
try {
37+
future.get();
38+
} catch (InterruptedException | ExecutionException e) {
39+
e.printStackTrace();
40+
}
41+
}
42+
43+
public String sendMessage(String message) {
44+
byte[] byteMsg = new String(message).getBytes();
45+
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
46+
Future<Integer> writeResult = client.write(buffer);
47+
48+
while (!writeResult.isDone()) {
49+
// do nothing
50+
}
51+
buffer.flip();
52+
Future<Integer> readResult = client.read(buffer);
53+
while (!readResult.isDone()) {
54+
55+
}
56+
String echo = new String(buffer.array()).trim();
57+
buffer.clear();
58+
return echo;
59+
}
60+
61+
public void stop() {
62+
try {
63+
client.close();
64+
} catch (IOException e) {
65+
e.printStackTrace();
66+
}
67+
}
68+
69+
public static void main(String[] args) throws IOException {
70+
AsyncEchoClient client = AsyncEchoClient.getInstance();
71+
client.start();
72+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
73+
String line = null;
74+
System.out.println("Message to server:");
75+
while ((line = br.readLine()) != null) {
76+
String response = client.sendMessage(line);
77+
System.out.println("response from server: " + response);
78+
System.out.println("Message to server:");
79+
}
80+
}
81+
82+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package com.baeldung.java.nio2.async;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.net.InetSocketAddress;
6+
import java.nio.ByteBuffer;
7+
import java.nio.channels.AsynchronousServerSocketChannel;
8+
import java.nio.channels.AsynchronousSocketChannel;
9+
import java.util.concurrent.ExecutionException;
10+
import java.util.concurrent.Future;
11+
12+
public class AsyncEchoServer {
13+
private AsynchronousServerSocketChannel serverChannel;
14+
private Future<AsynchronousSocketChannel> acceptResult;
15+
private AsynchronousSocketChannel clientChannel;
16+
17+
public AsyncEchoServer() {
18+
try {
19+
serverChannel = AsynchronousServerSocketChannel.open();
20+
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
21+
serverChannel.bind(hostAddress);
22+
acceptResult = serverChannel.accept();
23+
} catch (IOException e) {
24+
e.printStackTrace();
25+
}
26+
}
27+
28+
public void runServer() {
29+
try {
30+
clientChannel = acceptResult.get();
31+
if ((clientChannel != null) && (clientChannel.isOpen())) {
32+
while (true) {
33+
34+
ByteBuffer buffer = ByteBuffer.allocate(32);
35+
Future<Integer> readResult = clientChannel.read(buffer);
36+
37+
while (!readResult.isDone()) {
38+
// do nothing
39+
}
40+
41+
buffer.flip();
42+
String message = new String(buffer.array()).trim();
43+
if (message.equals("bye")) {
44+
break; // while loop
45+
}
46+
buffer = ByteBuffer.wrap(new String(message).getBytes());
47+
Future<Integer> writeResult = clientChannel.write(buffer);
48+
while (!writeResult.isDone()) {
49+
// do nothing
50+
}
51+
buffer.clear();
52+
53+
} // while()
54+
55+
clientChannel.close();
56+
serverChannel.close();
57+
58+
}
59+
} catch (InterruptedException | ExecutionException | IOException e) {
60+
e.printStackTrace();
61+
}
62+
63+
}
64+
65+
public static void main(String[] args) {
66+
AsyncEchoServer server = new AsyncEchoServer();
67+
server.runServer();
68+
}
69+
public static Process start() throws IOException, InterruptedException {
70+
String javaHome = System.getProperty("java.home");
71+
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
72+
String classpath = System.getProperty("java.class.path");
73+
String className = AsyncEchoServer.class.getCanonicalName();
74+
75+
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
76+
77+
return builder.start();
78+
}
79+
}

0 commit comments

Comments
 (0)