1

Hi i've looked at all the other questions similar to this that I could find and haven't been able to fix my last problem, though the answers to other questions got me this far.

I'm trying to write an array to a file, and so far I can do that, but the writer just writes everything on the same line. For some reason it won't accept my new line command (\n) when viewed in notepad.

An example to try and explain:

Array contents: test, test2, test3, test4

Write to file

File contents: test test2 test3 test4

Whereas i want the file to be: test test2 test3 test4

Below is the segment of my code to write to the file.

    public void save(String fileName) throws FileNotFoundException {

    try {

        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
        for ( int i = 0; i < nbrMovies; i++)
        {      
        writer.write(movies[i].getName() + " \n");
        }
        writer.close();
    } catch(IOException ex) {
        ex.printStackTrace();
    }
}

The file doesn't accept the "\n" command and instead just puts a little box next to the last movie added.

Any and all help would be greatly appreciated.

2
  • All text files should be able to accept "\n" character. What text editor you use to open the text file you just wrote? The text editor may not support reading unix style text file and show \n as a little box. Try using "\r\n" if you want to have Windows style text file. The line endings are different on these two OS. Commented Apr 28, 2011 at 15:16
  • Better yet, use writer.newLine() and it will insert the appropriate line ending for the platform. Commented Apr 28, 2011 at 15:47

8 Answers 8

3

First of all, you shouldn't close() the stream after every write; move the close() outside your loop, preferably into a finally block to ensure it is called. Second, rather than writing "\n", a better approach is

writer.write(movies[i].getName());
writer.newLine();
writer.flush(); //optional
Sign up to request clarification or add additional context in comments.

Comments

3

Take writer.close(); out of the for loop. Your code should be like this:-

 public void save(String fileName) throws FileNotFoundException {
    BufferedWriter writer = null;
    try {

        writer = new BufferedWriter(new FileWriter(fileName));
        for ( int i = 0; i < nbrMovies; i++)
        {      
          writer.write(movies[i].getName());
          writer.newLine();
      writer.flush();
        }

    } catch(IOException ex) {
        ex.printStackTrace();
    } finally{
        if(writer!=null){
            writer.close();
        }  
    }
}

3 Comments

This snippet won't compile because writer is not visible inside the finally block.
@Binil Thomas - Ofcourse - the purpose is not give production ready compile but to show where the problem is and how to do it better. Moving writer to outside the try catch is a very trivial task.
@CoolBeans - if its trivial why didn't you do it? I would of thought the purpose is to give a correct answer.
1

There is this writer.newLine(); and move the call to close out of the loop.

Comments

1
import java.io.*;

public class WriteChar 
{

    public static void main(String[] args) 
    {

        try
    {
       File f=new File("WriteChar.txt");
      char c[]={'a','b','c','d','e','f','g'};


       FileWriter out=new FileWriter(f);
       out.write(c);
       System.out.println("Done ..........");
       out.close();
    }

        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
    }

}

Comments

0

Wrap the FileWriter or BufferedWriter with a PrintWriter, and you will have access to the println(...) method.

Comments

0

Move the writer.close() outside the loop. Also, make sure that you flush the writer before closing it.

1 Comment

close() has an implicit flush()
0

Why don't you call close outside the loop?

Writer writer = null;
try {
    writer = new BufferedWriter(new FileWriter(fileName));
    for (Movie movie : movies) {      
        writer.write(movie.getName() + " \n");
    }
} catch(IOException ex) {
    ex.printStackTrace();
} finally {
    if (writer != null) {
        try {
            writer.close();
        } catch (IOException ignored) {
        }
    }
}

Comments

0

I agree with moving the writer.close() outside the loop. But there is a simpler way of doing what you want - rather than calling the newline function, just append carriage return instead of return at the end of the statement i.e.

change the statement: writer.write(movies[i].getName() + " \n"); to: writer.write(movies[i].getName() + " \r\n");

1 Comment

This will work because notepad requires both the \r and the \n to recognize a newline. So this isn't a problem with writing the file - rather it's a problem opening a linux-style file in notepad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.