File Writer - All going on one Line [duplicate] - java

I have coded the following FileWriter:
try {
FileWriter writer = new FileWriter(new File("file.txt"), false);
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
writer.write(sizeX);
writer.write(sizeY);
writer.flush();
writer.close();
} catch (IOException ex) {}
Now I want to insert a new line, just like you would do it with \n normally, but it doesn't seem to work.
What can be done to solve this?
Thank you.

If you want to get new line characters used in current OS like \r\n for Windows, you can get them by
System.getProperty("line.separator");
since Java7 System.lineSeparator()
or as mentioned by Stewart generate them via String.format("%n");
You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically
PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
// ^^^^^^^ will add OS line separator after data
(BTW System.out is also instance of PrintStream).

Try System.getProperty( "line.separator" )
writer.write(System.getProperty( "line.separator" ));

Try wrapping your FileWriter in a BufferedWriter:
BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();
Javadocs for BufferedWriter here.

Since 1.8, I thought this might be an additional solution worth adding to the responses:
Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException
StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());
If appending to the same file, perhaps use an Append flag with Files.write()
Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);

Try:
String.format("%n");
See this question for more details.

If you mean use the same code but add a new line so that when you add something to the file it will be on a new line. You can simply use BufferedWriter's newLine().
Here I have Improved you code also: NumberFormatException was unnecessary as nothing was being cast to a number data type, saving variables to use once also was.
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
writer.write(jTextField1.getText());
writer.write(jTextField2.getText());
writer.newLine();
writer.flush();
writer.close();
} catch (IOException ex) {
System.out.println("File could not be created");
}

Here "\n" is also working fine. But the problem here lies in the text editor(probably notepad). Try to see the output with Wordpad.

One can use PrintWriter to wrap the FileWriter, as it has many additional useful methods.
try(PrintWriter pw = new PrintWriter(new FileWriter(new File("file.txt"), false))){
pw.println();//new line
pw.print("text");//print without new line
pw.println(10);//print with new line
pw.printf("%2.f", 0.567);//print double to 2 decimal places (without new line)
}

I would tackle the problem like this:
BufferedWriter output;
output = new BufferedWriter(new FileWriter("file.txt", true));
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
output.append(sizeX);
output.append(sizeY);
output.newLine();
output.close();
The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?

using simple \n to break line in write file and normal output in java

Related

How can I get this buffered writer to write one line at a time? JAVA

I am creating a little program that will amend driver letters saved in a program file. The method works in the sense that it locates the file correctly and amends the drive letter correctly.
However when I open the file after it has been changed all the Directory listings are all on one line but they need to be 1 directory per line. I've tried saving each individual line to an Array List then printing them out like that but that didn't seem to work for me so was wondering if anyone could help?
Much appreciated.
P.S. Been messing around trying to make it work and also now ran into another issue where it is now printing them all out into one line but with spaces in between e.g:
S:\ D A T A\ S A G E\
public class copy
{
private String newDriveLetter;
private String line;
private Path[]sageFolders;
private FileReader fileReader;
private BufferedReader bufferedReader;
private FileWriter fileWriter;
private BufferedWriter bufferedWriter;
private List<String> lines = new ArrayList<String>();
public void scanFiles() throws IOException{
try
{
System.out.println("Sage 2015 is Installed on this machine");
File companyFile = new File(sageFolders[8] + "\\COMPANY");
fileReader = new FileReader(companyFile);
bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
if(line.contains("F"))
{
line = line.replace("F:\\","S:\\");
lines.add(line);
}
}
//Close the Readers
fileReader.close();
bufferedReader.close();
fileWriter = new FileWriter(companyFile);
bufferedWriter = new BufferedWriter(fileWriter);
for(String s : lines)
{
bufferedWriter.write(s);
}
bufferedWriter.flush();
bufferedWriter.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not Found: Moving onto next Version");
}
}
The problem is that readLine() reads a whole line, and then tosses away the line ending. From the documentation:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So you have to add it back again, possibly using the preferred line ending for your platform:
bufferedWriter.write(String.format("%s%n", s);
here %s is the String and %n is the platform dependent line ending.
Alternatively, as Ransom Briggs indicates, you may use newline(). newLine() is easier to read and will perform slightly better:
bufferedWriter.write(s);
bufferedWriter.newLine();
I've left the String.format method in as it is a more general approach of adding newlines to strings.
Try PrintWriter - so new PrintWriter(bufferedWriter).println(s).
Add this after bufferedWriter.write(s);:
bufferedWriter.write(System.getProperty("line.separator", "\n"));
This will add the system specific line separator, or "\n" if the system property is not set.

Writing to A Text File-Writing To Next Line

I'm appending to a text file but it won't go write to the next line, it keeps writing on the same line. I've tried .println() and PrintWriter.write("\r\n"); I'm not sure what else to do. (Windows System) Any help would be appreciated,
PrintWriter fOut;
try
{
fOut = new PrintWriter(new FileWriter("file_name.txt",true));
fOut.append("text\n");
fOut.close();
}
catch (IOException ex) {
Logger.getLogger(ScorePredictorFrame.class.getName()).log(Level.SEVERE, null, ex);
}
Assuming that file_name.txt already exists, and you want to write to the next line, I would do:
fOut.append("\r\ntext");
What is "text" in fOut.append("text\n");
if you are doing something like String text = ""; then you need to do it as fOut.append(text + "\n"); Else what you are doing is correct.
try
{
fOut = new PrintWriter(new FileWriter("file_name.txt",true));
fOut.println("text");
fOut.close();
}
The above code should work because according to the Java doc of the method it does enter the line separator
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
You can check the line.separator property using the following
final String lineSeparator = System.getProperty ( "line.separator" );

Create a new line in Java's FileWriter

I have coded the following FileWriter:
try {
FileWriter writer = new FileWriter(new File("file.txt"), false);
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
writer.write(sizeX);
writer.write(sizeY);
writer.flush();
writer.close();
} catch (IOException ex) {}
Now I want to insert a new line, just like you would do it with \n normally, but it doesn't seem to work.
What can be done to solve this?
Thank you.
If you want to get new line characters used in current OS like \r\n for Windows, you can get them by
System.getProperty("line.separator");
since Java7 System.lineSeparator()
or as mentioned by Stewart generate them via String.format("%n");
You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically
PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
// ^^^^^^^ will add OS line separator after data
(BTW System.out is also instance of PrintStream).
Try System.getProperty( "line.separator" )
writer.write(System.getProperty( "line.separator" ));
Try wrapping your FileWriter in a BufferedWriter:
BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();
Javadocs for BufferedWriter here.
Since 1.8, I thought this might be an additional solution worth adding to the responses:
Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException
StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());
If appending to the same file, perhaps use an Append flag with Files.write()
Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);
Try:
String.format("%n");
See this question for more details.
If you mean use the same code but add a new line so that when you add something to the file it will be on a new line. You can simply use BufferedWriter's newLine().
Here I have Improved you code also: NumberFormatException was unnecessary as nothing was being cast to a number data type, saving variables to use once also was.
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
writer.write(jTextField1.getText());
writer.write(jTextField2.getText());
writer.newLine();
writer.flush();
writer.close();
} catch (IOException ex) {
System.out.println("File could not be created");
}
Here "\n" is also working fine. But the problem here lies in the text editor(probably notepad). Try to see the output with Wordpad.
One can use PrintWriter to wrap the FileWriter, as it has many additional useful methods.
try(PrintWriter pw = new PrintWriter(new FileWriter(new File("file.txt"), false))){
pw.println();//new line
pw.print("text");//print without new line
pw.println(10);//print with new line
pw.printf("%2.f", 0.567);//print double to 2 decimal places (without new line)
}
I would tackle the problem like this:
BufferedWriter output;
output = new BufferedWriter(new FileWriter("file.txt", true));
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
output.append(sizeX);
output.append(sizeY);
output.newLine();
output.close();
The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?
using simple \n to break line in write file and normal output in java

BufferedReader then write to txt file?

Is it possible to use BufferedReader to read from a text file, and then while buffered reader is reading, at the same time it also storing the lines it read to another txt file using PrintWriter?
If you use Java 7 and want to copy one file directly into another, it is as simple as:
final Path src = Paths.get(...);
final Path dst = Paths.get(...);
Files.copy(src, dst);
If you want to read line by line and write again, grab src and dst the same way as above, then do:
final BufferedReader reader;
final BufferedWriter writer;
String line;
try (
reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
writer = Files.newBufferedWriter(dst, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
doSomethingWith(line);
writer.write(line);
// must do this: .readLine() will have stripped line endings
writer.newLine();
}
}
To directly answer your question:
you can, and you can also use BufferedWriter to do so.
BufferedReader br = new BufferedReader(new FileReader(new File("Filepath")));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Filepath")));
String l;
while((l=br.readLine())!=null){
... do stuff ...
bw.write("what you did");
}
bw.close();
If you just need to copy without inspecting the data, then it's a one liner:
IOUtils.copy(reader, printWriter);
Yes. Open the BufferedReader, and then create a PrintWriter. You can read from the stream as you write to the writer.

Strings are not written to a new line

Following snippet attempts to write the name of directories and files present in some directory to a text file.Each name should be written to a separate line.Instead it prints each name on the same line. Why is it so ?
try {
File listFile = new File("E:" + System.getProperty("file.separator") + "Shiv Kumar Sharma Torrent"+ System.getProperty("file.separator") +"list.txt");
FileWriter writer = new FileWriter(listFile,true);
Iterator iterator = directoryList.iterator();
while(iterator.hasNext()) {
writer.write((String)iterator.next());
writer.write("\n"); // Did this so each name is on a new line
}
writer.close();
}catch(Exception exc) {
exc.printStackTrace();
}
output:
Where am i making a mistake ?
Whenver you need textual formatting always use PrintWriter.
The right way of doing is to wrap the writer inside a PrintWriter and use println() method, like:
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println();
If you are using Windows, use \r\n instead of \n.
or for OS-independent, use:
System.getProperty("line.separator");
You should write your next line as "\r\n" if you are on a Windows platform.
The next line for Windows is "\r\n"
The next line for Mac is "\n"
Alternatively, use System.getProperty("line.separator") for your line break. It automatically determines the right line break for the system it is running on. This should be the best practice since Java is expected to perform the same on different OS-es.
If you are going to use BufferedWriter :
File f = new File("C:/file.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.write("Hello");
bw.newLine(); // new line
bw.write("How are you?");
bw.close();

Categories