Question

I know this is very basic stuff but for some reason I'm having problems with a bufferedReader/ Writer. I am trying to get the first line of text and return it to another method. However, for some reason the writer doesn't seem to be writing to the temp file and it isn't changing the name of the temp file either.

By throwing a few print statements I have been able to figure out:

  1. The while loop is operating correctly
  2. The if else statement is operating correctly
  3. The tempFile is not writing to a text file correctly
  4. The tempFile is not renaming correctly
  5. There are no errors being thrown

    private static String wavFinder() throws IOException{

        String currentWav=null;
        int x = 1;
        File inputFile = new File("C:\\convoLists/unTranscribed.txt");
        File tempFile = new File("C:\\convoLists/unTranscribedtemp.txt");
        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
        String currentLine = null;
    
        while((currentLine = reader.readLine()) != null) {
            if(x == 1){
                currentWav = currentLine;
            }
            else{
            writer.write(currentLine);
            }
            x = 2;
        }
        boolean successful = tempFile.renameTo(inputFile);      
        System.out.println("Success: " + successful);
        System.out.println("currentWav = " + currentWav);
        return currentWav;
    }
    

Here is the method I am using. If you notice anything please let me know and if you have any questions I will be sure to answer them quickly. Thank you :)

Was it helpful?

Solution

  1. First flush the steam(writer) and close them.
  2. You can not have two files with same name. You are trying to rename the temp file with input file. You need to delete input file and then rename it to that.

    reader.close(); writer.flush(); writer.close(); inputFile.delete();

Add these lines before rename and it will work

OTHER TIPS

Close your buffers before trying to call renameTo.

reader.close()
writer.close()

File inputFile = new File("C:\convoLists/unTranscribed.txt"); File tempFile = new File("C:\convoLists/unTranscribedtemp.txt");

Why you have different signs for path?

Always should be //.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top