简体   繁体   中英

I can't write two times over the same file (java)

I am writing to a text file, the first time the a FileOutputStream, and the second time through a FileWriter.

The FileOutputStream seems to be writing to the text file just fine. However, the FileWriter does not. After the FileWriter executes, the content of the file disappears, however it does not get replaced by what the FileWriter is supposed to write. Below is my code:

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();
        }

You have a Scanner and a FileWriter open to the same pathname at the same time, which is "unhealthy".

Read and close, then create the Writer.

And make sure to call close() after writing! This is missing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM