Pregunta

I want to write a few arguments in a .txt file and I want to sort them. To do that I want to go to the next line for every groop of arguments but I dont know how to do that.I have tried the: x.nextLine(); statement, but that is only for scanning and not for formatting.

How can I go to the next line of a file while formatting? Is there another statement for that?

This is the code I created:

try{
    w = new Formatter("data.txt");
}
catch(Exception e){
        JOptionPane.showMessageDialog(null, "Fatal Error, please Reboot or reinstal program", "Error", JOptionPane.PLAIN_MESSAGE);
}

w.format("%s,%s,%s,%s%n", book,code,author,editor);
w.close();
¿Fue útil?

Solución

You write

w.format("%s,%s,%s,%s%n", book,code,author,editor);

and I assume you want a newline where you write %n. But newline is \n, so change your code to

w.format("%s,%s,%s,%s\n", book,code,author,editor);

Also, you may want to revise the error catching logic in the program: right now if opening the file fails, you show an error message, which is good, but after that your program continues execution and will crash and burn on the first write operation...

EDIT: every time you execute the line w.format("%s,%s,%s,%s\n", book,code,author,editor); a line terminated by a new line will be added to the file, as long as you don't close the file or restart the program, because the Javadoc for the constructor you use says:

fileName - The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

So, if you need a file that grows instead of being overwritten you should use one of the other available constructors, eg one accepting an Appendable as argument. This would lead to the following code:

FileWriter fstream = new FileWriter("data.txt",true);
Formatter w = new Formatter(fstream);

// do whatever your program needs to do

w.close();

Of course surrounded by the necessary exception handling.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top