我不能在同一个文件上写两次(java)



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

您有一个ScannerFileWriter同时打开到同一路径名,这是"不健康的"。

读取并关闭,然后创建Writer。

写完之后一定要调用close()!这个不见了。

相关内容

  • 没有找到相关文章

最新更新