I am wondering why nothing is being written to my file. I have the file in my project space, anytime I open it, there is nothing there. I am essentially trying to write to a file, close it, then appened to it again. so on so forth.
public static void writeToFile(String name) throws IOException{
FileWriter fw = new FileWriter("myFile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.println(name);
fw.close();
}
in my main I am just calling the method with a random string in the parameter
Try adding flush() before you close the file. PrintWriter does not have automatic flushing
This worked for me
FileWriter fWriter;
File mFile = new File("fully qualified file name");
try{
fWriter = new FileWriter(mFile, true);
fWriter.write("File content");
fWriter.flush();
fWriter.close();
}catch(Exception e){
e.printStackTrace();
}
Related
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");
}
Hello so today ive been working with txt docs and writing files so i currently have this code
try {
File file = new File("./Data/Email/Subscribed.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(player.playerEmail + ",");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
So my question is how do i make it so every time something is written to the file it writes to the next line down
Wrap the BufferedWriter in a PrintWriter and replace the write() calls with println().
Now, every call inserts text on a new line.
I have an application that creates a .txt file. I want to overwrite it. This is my function:
try{
String test = "Test string !";
File file = new File("src\\homeautomation\\data\\RoomData.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}else{
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
What should I put in the else clause, if the file exists, so it can be overwritten?
You don't need to do anything particular in the else clause. You can actually open a file with a Writer with two different modes :
default mode, which overwrites the whole file
append mode (specified in the constructor by a boolean set to true) which appends the new data to the existing one
You don't need to do anything, the default behavior is to overwrite.
No clue why I was downvoted, seriously... this code will always overwrite the file
try{
String test = "Test string !";
File file = new File("output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
Just call file.delete() in your else block. That should delete the file, if that's what you want.
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.
The Below one line code will help us to make the file empty.
FileUtils.write(new File("/your/file/path"), "")
The Below code will help us to delete the file .
try{
File file = new File("src\\homeautomation\\data\\RoomData.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
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();
i am new developer in android.i would like to write some content to a file i have used a method to write into a file as follows
public void writeFile(String path,String text){
try{
Writer output = null;
File file = new File(path);
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
System.out.println("Your file has been written");
}
catch (Exception e) {
e.printStackTrace();
}
here i am passing path of a file and text to write.if i use in this way i can write the data but the previous data is losing.
how can i append or insert the latest text into a file without losing previous text?
Thanks in advance
Try this. Change this line ...
output = new BufferedWriter(new FileWriter(file));
to
output = new BufferedWriter(new FileWriter(file, true));
The true indicates that you want to append not overwrite
Have a look here and try:
new FileWriter(file, true);
the boolean indicates whether or not to append to an existing file.