我正在写一个文本文件,第一次是FileOutputStream,第二次是通过FileWriter。
FileOutputStream似乎可以将其写入文本文件。但是,FileWriter没有。 FileWriter执行后,文件的内容消失了,但是并没有被FileWriter应该写的内容代替。下面是我的代码:
try {
serverSocket = new ServerSocket(850);
if(!serverSocket.isBound())
System.out.println("Sever Socket not Bounded...");
else
System.out.println("Server Socket bounded to Port : "+serverSocket.getLocalPort());
clientSocket = serverSocket.accept();
if(!clientSocket.isConnected())
System.out.println("Client Socket not Connected...");
else
System.out.println("Client Socket Connected : "+clientSocket.getInetAddress());
InputStream in = clientSocket.getInputStream();
int byteRead = 0;
byte[] byteArray = new byte[1024];
//Write the action in a file
actionFile = new File("C:\\Users\\Khoury\\Documents\\MATLAB\\FYP.txt");
FileOutputStream fos = new FileOutputStream(actionFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while((byteRead = in.read(byteArray, 0, byteArray.length))> 0){
bos.write(byteArray, 0, byteRead);
}
serverSocket.close();
clientSocket.close();
in.close();
bos.close();
fos.close();
Scanner scan = new Scanner(actionFile);
actionChar = scan.next().charAt(0);
if(actionChar == '1' || actionChar == '2'){
FileWriter fw = new FileWriter(actionFile);
BufferedWriter bw2 = new BufferedWriter(fw);
PrintWriter pw2 = new PrintWriter(bw2);
pw2.write('r');
}
System.out.println("Action here: " + actionChar);
}catch (IOException e) {
e.printStackTrace();
}
最佳答案
您同时有一个Scanner
和FileWriter
打开到相同的路径名,这是“不健康的”。
阅读并关闭,然后创建Writer。
并确保在编写后调用close()!这不见了。
关于java - 我不能在同一个文件上写两次(java),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23215188/