Write different lines to file - java

I have this method that writes to a file every time it's called:
public void writeToFile(String ins) {
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(ins);
bw.newLine();
bw.close();
fw.close();
}
But it only writes on the very first line of the file.
So, if I called it once with "Hello" and then again with "World", the file would contain "World", but the result I'm looking for is:
Hello
World
I tried using BufferedWriter.newLine() before and after writing the string but the result is the same?

You have to use FileWriter(String fileName, boolean append)
FileWriter fw = new FileWriter(f, true);

read the documentation of FileWriter:
FileWriter(File file, boolean append)
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
and you see, that you need to set the append value to true:
FileWriter fw = new FileWriter(f, true);

The point is: your code does what it is supposed to do - it uses a FileWriter, which by default will create a new, empty file; it writes one string; and closes the FileWriter.
If you want to write more than one line; you either have to
use the FileWriter in APPEND mode when doing later writes (by using that second, boolean argument for the FileWriter constructor with true)
change your method to take a list of strings, and write all of them at once

you can use a escape character:
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
I recommend you to use resource try to allow java to close the file when it will necessary
public void writeToFile(String ins) {
String fileName= "file.txt";
try (FileWriter fileWritter = new FileWriter(fileName, true)) {
fileWritter.write(ins + "\r\n");
} catch (IOException ex) {
}
}
give to this method a empty string "" to insert in the file a "Enter"

Related

Write to a file without overwriting the existing data within that file

I have a filewriter that takes String data from the user and writes it on the file. But the filewriter replaces the already existing data in that file. How do I prevent it from doing it? I just want to keep adding information without writing over something.
Here is the code
String info = scan.nextLine();
File myFile = new File ("/home/greg/workspace/Mavericks/fred.txt");
FileWriter writer = new FileWriter (myFile);
writer.write(register);
writer.flush();
Thanks. I fixed that. Now I just want to make the writer write using spaces. When I write to the file it just keeps writing within the same line.
You need use the boolean value true. From docs
public FileWriter(String fileName,
boolean append)
throws IOException
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
Use second parameter of FileWriter, which is defining if you want to append or not. Just set it to true.
BufferedWriter writer = new BufferedWriter(new FileWriter(
sFileName, true));
Add \n after each line.
Use
new FileWriter(myFile, true)
The second parameter is for appending.
Api:
FileWriter(File file, boolean append)
Constructs a FileWriter object given a File object.
http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
FileWriter has an optional boolean in the constructor, which declares if it should be appended or not.
FileWriter writer = new FileWriter(..., true)
BufferedWriter bw = new BufferedWriter(new FileWriter(filename ,true));

Writing new line notepad

Simply trying to move to a new line after printing each element inside of notepad. Some searching has yielded uses of \r\n, but that doesn't seem to work either.
for(String element : misspelledWords)
{
writer.write(element + "\n");
}
try this
BufferedWriter writer = new BufferedWriter(new FileWriter("result.txt"));
for (String element : misspelledWords) {
writer.write(element);
writer.newLine();
}
Adding line separator at the end (like "\n") should work on most OS,but to be on safer side
you should use System.getProperty("line.separator")
Open your file in append mode like this
FileWriter(String fileName, boolean append) when you want to make an object of class FileWrite
in constructor.
File file = new File("C:\\Users\\Izak\\Documents\\NetBeansProjects\\addNewLinetoTxtFile\\src\\addnewlinetotxtfile\\a.txt");
try (Writer newLine = new BufferedWriter(new FileWriter(file, true));) {
newLine.write("New Line!");
newLine.write(System.getProperty( "line.separator" ));
} catch (IOException e) {
}
Note:
"line.separator" is a Sequence used by operating system to separate lines
in text files
source:
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Write text to the next line using Java

So i'm trying to write stuff to a file and it works but when i call this method more than once it removes the previous stuff i wrote with the new. So i wonder what should i do so the method wont remove my previous text that i've added to the file and adds the new text to the
next line.
public static void writetofile(String id, String content) throws IOException
{
try {
FileWriter filewriter = new FileWriter("Random.txt");
BufferedWriter out = new BufferedWriter(filewriter);
out.write(id+" "+ content);
out.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
FileWriter filewriter = new FileWriter("Random.txt", true);
As per java doc
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file rather than the beginning
There is constructor signature of FileWriter with a boolean parameter which controls append behavior. Providing that appending is what you want, you should construct the FileWriter with this boolean set to true:
FileWriter filewriter = new FileWriter("Random.txt", true);
Note, that in case of single parameter constructor the output is written to the beginning of the file (see the implementation of FileOutputStream which is wrapped by FileWriter), so calling single parameter constructor is equivalent to setting the boolean parameter to false.

Writing to a file from different methods

I've been working on a small project in Java. The program writes to a log file from different methods . But each time a method is used , the content of the file gets deleted and all what's written in it is the result of the last method.
here's a code snippet of the program :
// dir , log_file , exp_date and amount are declared in the code removed
public static void WriteHeader() throws IOException
{
FileWriter fileWriter = new FileWriter(dir+"/"+log_file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
Console console = System.console();
exp_date = console.readLine("Enter a string here: ");
bufferedWriter.write(exp_date);
bufferedWriter.close();
}
public static void WriteNewLine() throws IOException
{
FileWriter fileWriter = new FileWriter(dir+"/"+log_file);
BufferedWriter bufferedWriter2 = new BufferedWriter(fileWriter);
Console console = System.console();
amount = console.readLine("Enter another string here :");
bufferedWriter2.newLine();
bufferedWriter2.write(amount);
bufferedWriter2.close();
}
You need to create the writer in append mode http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
You need to open file in append mode otherwise once you close the file and reopen it to write, it would erase previous data. http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String, boolean)
FileWriter fileWriter = new FileWriter(dir+"/"+log_file, true);
FileWriter fw = new FileWriter(file, true);
I am pretty sure FileWriter has an overloaded constructor for appending to a file instead of overwriting a file
I would also check if the file exists first.
file.exists();

How to write mutilple lines in a text file by calling same method different time?

I come up with a problem.
This is my method below:
public void someMethod()
{
StringBuilder newFile = new StringBuilder();
String edited = "My String Line";
newFile.append(edited);
newFile.append("\n");
FileWriter fstreamWrite = new FileWriter("transaction.txt");
BufferedWriter out = new BufferedWriter(fstreamWrite);
out.write(newFile.toString());
out.close();
}
And when I am calling this method in my main class more than one time so this code is creating my transaction.txt with a line "My String Line". But when I am to call this method more than one time to write the "My String Line" several time, it just overriding the line and not giving me the output like.
My String Line
My String Line
My String Line
When I call the method 3 times.
Any idea how to write the same line multiple times as by calling the same method multiple times?
I think you want to append to a file . Then you can use the constructor FileWriter(java.io.File,boolean):
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file rather than the beginning
Hence change the code to :
new FileWriter("transaction.txt",true);
To write a new line to the file , use BufferedWriter#newLine().
Writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.
It is a bad idea to open a file just to write a few lines there. A better approach is to pass the Writer to your method as argument:
public void someMethod(BufferedWriter writer) throws IOExcpetion {
// setup your data to write
StringBuilder sb = .....
// actually write it
writer.write(sb.toString());
writer.newLine()
}
Once you have this, you can use it in a setting like this:
BufferedWriter bw = null;
try {
bw = .... // open the writer
while (...) {
someMethod(bw);
}
bw.close();
} catch (IOException io) {
// handle IOException here
}
...
finally {
// make sure bw is closed
}

Categories

Resources