Search code examples
javafileinputoutputprintwriter

PrintWriter doesn't save all characters


class Start 
{
    File plikIN;
    Scanner in;
    PrintWriter out;

    Start(String input, String output)
    {
        plikIN = new File(input);
        try{
        in = new Scanner(plikIN);
        out = new PrintWriter(output);
        } catch (FileNotFoundException e) {System.out.println("Nie odnaleziono podanego pliku\n"+e);}
    }

    private void saveing() throws IOException
    {
        String word;
        int wordLength;
        String wordTable[];
        char c;

        while((word = in.next()) != null)
        {
            wordLength = word.length();
            wordTable = new String[wordLength];
            for(int k=0; k<wordTable.length; ++k)
            {
                c = word.charAt(k); 
                out.println(c);
            }   
        }
        out.close();
    }

    public static void main(String[] args) throws IOException
    {
        String nazwaPlikuWejsciowego = args[0];
        String nazwaPlikuWyjsciowego = args[1];
        Start doit = new Start(nazwaPlikuWejsciowego, nazwaPlikuWyjsciowego);
        doit.saveing();

    }
}

My problem is saving to file. After the saveing method above, the file does not contain any single character. When I move the out.close() to while for instance, the file contains one word. When out.close() is in for, the program saves one character only. Why?


Solution

  • add out.flush() before out.close().

    You need to flush the bytes to disk before you close it..