62,614
社区成员
发帖
与我相关
我的任务
分享
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardOpenOption.*;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
public class ClassA extends Thread{
public static void main(String[] args){
Path path = Paths.get(System.getProperty("user.dir")).resolve("data.bin");
Thread thread = new ClassA(path);
thread.start();
}
public ClassA(Path path){
this.path = path;
}
@Override
public void run(){
try(BufferedReader keyboard = new BufferedReader(
new InputStreamReader(System.in));){
String content = null;
BufferedWriter writer = null;
while(true){
writer = new BufferedWriter(
new OutputStreamWriter(
Files.newOutputStream(path,CREATE,WRITE,APPEND)));
System.out.println("Input content:");
content = keyboard.readLine() + System.lineSeparator();
writer.write(content);
writer.close();
}
}catch(IOException e){
e.printStackTrace();
System.exit(1);
}
}
private Path path = null;
}
class ClassB extends Thread{
public static void main(String[] args){
Path path = Paths.get(System.getProperty("user.dir")).resolve("data.bin");
Thread thread = new ClassB(path);
thread.start();
}
public ClassB(Path path){
this.path = path;
}
@Override
public void run(){
try{
BufferedReader reader = null;
String content = null;
HashMap<Integer,String> contents = new HashMap<>();
while(true){
reader = new BufferedReader(
new InputStreamReader(
Files.newInputStream(path,READ)));
int line = 0;
while((content = reader.readLine()) != null){
contents.put(line ++ , content);
}
reader.close();
if(line != lineCount){
for(int i = lineCount ; i < line ; i ++){
System.out.println("新增数据:<第" + (i + 1) + "行>:" + contents.get(i));
}
lineCount = line;
}
}
}catch(IOException e){
e.printStackTrace();
System.exit(1);
}
}
private static int lineCount = 0;
private Path path = null;
}