Write text to the next line using Java - 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.

Related

Write different lines to file

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"

Writing in .txt without erasing the previous

I have notice in my code that, whenever I enter a new input, the previous text I entered is gone and completely being replace by the new one.
How do I create a new one without removing the previous text?
Here's is my code:
String pangalan = nameField.getText().trim();
String edad = age.getText().trim();
if(pangalan.length()!=0&&edad.length()!=0){
JLabel l1 = new JLabel("Submit Success!");
mainPanel.add(l1);
l1.setBounds(70,115,100,100);
try{
input = new Formatter(new File("jj.txt"));
}//try
catch(Exception i){
System.out.println("File not found!");
}//catch
input.format("%s %s",pangalan,edad);
input.close();
}
These are the constructors on the java FileWriter 1.7
Constructor and Description
FileWriter(File file) // Constructs a FileWriter object given a File object.
FileWriter(File file, boolean append) // Constructs a FileWriter object given a File object.
FileWriter(FileDescriptor fd) //Constructs a FileWriter object associated with a file descriptor.
FileWriter(String fileName) // Constructs a FileWriter object given a file name.
FileWriter(String fileName, boolean append) // Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Refer to the API for more info.
I used the FileWriter(File,boolean) as said by MadProgrammer :) And it worked perfectly :)
you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append) constructor.
output = new BufferedWriter(new FileWriter(my_file_name, true));
example :
public static void main(String[] args) {
Writer output;
try {
output = new BufferedWriter(new FileWriter(("E:\\test.txt"), true));
output.write("current line");
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
output will be ::
Hope it may help you.

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));

Java FileWriter not actually changing file at all

I have been looking for the past hour or so trying to find the reason for this, but have found nothing. It is a very small text file (only 4 characters at most), thus the reason I did not bother with a BufferedReader or BufferedWriter. The problem lies in the fact that while I have the writer put the variable into the file and even close the file, it does not actually keep the change in the file. I have tested this by checking the file immediately after running the method containing this code.
try {
int subtract = Integer.parseInt(secMessage[2]);
try {
String deaths = readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset());
FileWriter write = new FileWriter("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt");
int comb = Integer.parseInt(deaths) - subtract;
write.write(comb);
write.close();
sendMessage(channel, "Death count updated to " + comb);
} catch (IOException e) {
e.printStackTrace();
}
} catch (NumberFormatException e) {
e.printStackTrace();
sendMessage(channel, "Please use numbers to modify death count");
}
EDIT: Since it was asked, here is my readFile message:
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
I have already tested it and it returns the contents without error.
EDIT2: Posting the readFile method made me think of something to try, so I removed the call to it (code above also updated) and tried it again. It now writes to the file, but does not write what I want. New question will be made for this.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
You're trying to write a file named after the contents of deaths.txt. It's possible that you intend to be writing to the file itself.
From http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
FileWriter(String fileName)
Constructs a FileWriter object given a file name.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
Currently you are using the contents of the file instead of the file name.

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