gpt4 book ai didi

java - 我无法在同一个文件上写入两次(java)

转载 作者:行者123 更新时间:2023-12-01 23:03:05 25 4
gpt4 key购买 nike

我正在写入一个文本文件,第一次是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com