Search code examples
javawriter

Java program only writing last line?


My issue is that with the reader the writer is only outputting what is on the last line of the file and I'm not sure why as far as I know I'm not accidentally closing it or any error similar to that. This is the code I'm using for the writer

private static void processhtml(String UserFile) throws FileNotFoundException {
    Scanner s = new Scanner(new BufferedReader(
            new FileReader(UserFile))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");

    //splits the file at colons
    int count=0;
    String line="";
    String[] words=new String[40];
    try{
        String fileName="test"+count+".html";
        PrintWriter writer = new PrintWriter(fileName, "UTF-8");
        while (s.hasNext()) {
             line =s.nextLine();
             words = line.split("\\s*:\\s*");

             for(int i=0;i<words.length;i++){
                 writer.println(words[i]);
             }

             writer.close();
             writer.flush();
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

Solution

  • It looks like you're creating your Writer outside the loop, but then closing it from within the loop. Are you sure it's only the last line you're getting? My guess would be you're only getting the first line.

    It seems like this needs to move after the next curly brace:

            writer.close();
            writer.flush();
    

    And you should probably switch the ordering since flush() won't do anything if the stream is already closed (though often close() calls flush() anyway).