我正在写一个文本文件,第一次是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();
}
答案 0 :(得分:3)
您有Scanner
和FileWriter
同时对同一个路径名开放,这是“不健康”。
阅读并关闭,然后创建Writer。
确保在写完后调用close()!这是缺失的。