Writing to a file from different methods - java

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

Related

How to create and output to files in Java

My current problems lie with the fact that no matter what solution I attempt at creating a file in Java, the file never, ever is created or shows up.
I've searched StackOverflow for solutions and tried many, many different pieces of code all to no avail. I've tried using BufferedWriter, PrintWriter, FileWriter, wrapped in try and catch and thrown IOExceptions, and none of it seems to be working. For every field that requires a path, I've tried both the name of the file alone and the name of the file in a path. Nothing works.
//I've tried so much I don't know what to show. Here is what remains in my method:
FileWriter fw = new FileWriter("testFile.txt", false);
PrintWriter output = new PrintWriter(fw);
fw.write("Hello");
I don't get any errors thrown whenever I've run my past code, however, the files never actually show up. How can I fix this?
Thank you in advance!
There are several ways to do this:
Write with BufferedWriter:
public void writeWithBufferedWriter()
throws IOException {
String str = "Hello";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(str);
writer.close();
}
If you want to append to a file:
public void appendUsingBufferedWritter()
throws IOException {
String str = "World";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(str);
writer.close();
}
Using PrintWriter:
public void usingPrintWriteru()
throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
Using FileOutputStream:
public void usingFileOutputStream()
throws IOException {
String str = "Hello";
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
Note:
If you try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown.
It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it.
In output stream, the close() method calls flush() before releasing the resources which forces any buffered bytes to be written to the stream.
Source and More Examples: https://www.baeldung.com/java-write-to-file
Hope this helps. Good luck.
A couple of things worth trying:
1) In case you haven't (it's not in the code you've shown) make sure you close the file after you're done with it
2) Use a File instead of a String. This will let you double check where the file is being created
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
FileWriter fw = new FileWriter(file, false);
fw.write("Hello");
fw.close();
As a bonus, Java's try-with-resource will automatically close the resource when it's done, you might want to try
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
try (FileWriter fw = new FileWriter(file, false)) {
fw.write("Hello");
}

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"

Multiple Lines into One Text File? - Java

How can I save multiple lines into One Text File?
I want to print "New Line" in the same Text File every time the code is executed.
try {
FileWriter fw = new FileWriter("Test.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("New Line");
pw.close();
}
catch (IOException e)
{
System.out.println("Error!");
}
I'm able to create a new file but can't create a new line every time the code is executed.
Pass true as a second argument to FileWriter to turn on "append" mode.
FileWriter fw = new FileWriter("filename.txt", true);
That will make your file to open in the append mode, which means, your result will be appended to the end of the file each time you'll write to the file. You can also write '\n' after each content writing so that it will inserts a new line there.
You are creating a new line every time it is run, the problem is that you are truncating the file when you open it. I suggest you append to the file each time.
try (FileWriter fw = new FileWriter("Test.txt", true); // true for append
PrintWriter pw = new PrintWriter(fw)) {
pw.println("New Line");
} // try-with-resource closes everything.
Note: openning and closing a file for each line is expensive, If you do this a lot I suggest leaving the file open and flushing the output each time.
You are doing this:
FileWriter fw = new FileWriter("Test.txt");
which is overwriting the file every time you execute that line...
BUT you need instead to append the data to the file
FileWriter fw = new FileWriter("Test.txt", true);
take a look at the constructor in the doc
You need to open the file in append mode. You can do that as follows:
FileWriter fw = new FileWriter("Test.txt", true);
Here is the documentation for the same.

File writing issue

This is my below code where I am trying to write the data in the file. but the values are not successfully written in the file also didn't thrown any exception as well. so I feel it could be an file permission issue. if that is the case then the exception would be thrown.
public void setPrice(PriceDetails priceDetails)throws IOException {
priceoutputStream = new FileOutputStream(cacheFile);
String priceDetailsString = priceDetails.toString();
String valueString = priceDetailsString.substring(priceDetailsString.indexOf("=")+1);
priceDetailsProperties.setProperty(formatPLU(priceDetails.getPlu()),valueString)??;
priceDetailsProperties.store(priceoutputStream,null);
priceoutputStream.close();
}
Could you help me out?
I think we can simply do this using another way, as there is no binary data to write or read we can use Reader and Writer with Buffers.
Please try the following code to write it to the file:
File f = new File("Path");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Your Data");
bw.close();

Appending to a file in java

I am working on a project. For the project I am using GUI and I want to write a number to a file. I have been successful, and I can write the number to the file that i want to. My problem that hopefully someone can give insite to is that everytime i write a number to a file the new number replaces the old one. How would i go about keeping the current info in the file. My code is:
public static void writeCodeFile (String filename, int x, String userName) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
outputWriter.newLine();
outputWriter.write(userName +":"+ Integer.toString(x));
outputWriter.newLine();
outputWriter.flush();
outputWriter.close();
}
Use append mode:
outputWriter = new BufferedWriter(new FileWriter(filename, true));
When you create the FileWriter, add a second parameter "true" to go into append mode.

Categories

Resources