FileWriter writing into file - java

How do I use FileWriter to actually write into a file and then open it on notepad and see what I wrote? This is what I tried so far:
package Experimental;
import java.io.*;
public class IO {
public static void main (String args[]) {
File f = new File("testFile.txt");
//Outputting into a file
try {
PrintWriter filePrint = new PrintWriter(
new BufferedWriter(new FileWriter(f,true))
);
filePrint.println("testing, testing, printing into a file (apparently)");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

Don't forget to close your FileWriter once you are done writing to it.

You should flush and close the PrintWriter like this:
File file = new File("testFile.txt");
PrintWriter filePrint = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
try
{
try
{
filePrint.println("testing, testing, printing into a file (apparently)");
filePrint.flush();
}
finally
{
filePrint.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}

Related

Why doesn't it work correctly to write in the file?

I am currently trying to program a small API, but with my writeToFile method, even if I use true in the method, it deletes everything that is in the file and only writes in the text of the user (#param text).
What did I do wrong ? I tried to print the string, but it appears to be empty. If I only use the readFile method of mine, it reads out the whole file correctly.
Need help.
package at.tornaduuu.usefullapi.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileUtils {
public static void writeToFile(String text, File file, boolean keepIndexText) {
try {
String indexText = "";
FileWriter fw = new FileWriter(file);
if (keepIndexText) {
indexText = FileUtils.readFile(file);
System.out.println(indexText);
FileUtils.clearFile(file);
fw.write(indexText + text);
fw.close();
}
else {
fw.write(text);
fw.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void clearFile(File file) {
try {
FileWriter fw = new FileWriter(file);
fw.write("");
fw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static String readFile(File file) {
String fileIndex = "";
int unicode;
try {
FileReader fr = new FileReader(file);
try {
while ((unicode = fr.read()) != -1) {
fileIndex += (char) unicode;
}
fr.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return fileIndex;
}
}
You are not appending to file, you are just rewriting it. That's because FileWriter is not set to append. You can change this:
FileWriter fw = new FileWriter(file); //rewrites file every time write() method is called
to:
FileWriter fw = new FileWriter(file,true); //append text in file when write() is called
and it should work.
You are calling FileWriter(File) which in turn will call FileOutputStream(String name, append = False). So your file is getting truncated before you read content.
There is another constructor FileWriter(File file, boolean append) that you can use with keepIndexText, in such case your FileUtils.clearFile(file); is pretty useless.

Is there any usage for nested try if without catch?

Came across the below code from a Java book
public void writeFile(String fileName, String content){
File file = new File(fileName);
try {
try (PrintWriter output = new PrintWriter(new FileWriter(file))) {
output.println(content);
output.println();
output.println("End of writing");
}
System.out.println("File been written successfully");
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
Nothing is wrong with the above code, I simply couldn't see the point of having a nested try that doesn't define an inner catch block. Or is there any purpose of doing so in which I've missed it?
Revised code:
public void writeFile(String fileName, String content){
File file = new File(fileName);
try (PrintWriter output = new PrintWriter(new FileWriter(file))) {
output.println(content);
output.println();
output.println("End of writing");
System.out.println("File been written successfully");
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
The inner try is a try-with-resources:
try (PrintWriter output = new PrintWriter(new FileWriter(file)))
it means, that it manages the resource - PrintWriter - opens it and closes it after every statement in this try is conducted. The outer try is used to catch the error.
Your revised code what Petter Friberg proposed, is equivalent.

Why fileWriter is not saving the content to my file?

It's not showing any error but the content should be saved to my file, which is not saving...
import java.util.Scanner;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileReadLine {
public static void main(String[] args) {
try {
String str;
Scanner sc=new Scanner(System.in);
do {
System.out.println("Enter your lines");
str=sc.nextLine();
FileWriter fw = new FileWriter("C:/test/abcd.txt");
if(!str.equals("stop"))
fw.write(str);
fw.write("\n");
fw.close();
} while(!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
}
}
}
please correct my code if i am wrong
You are trying to create a new file inside the loop. So it gets overridden. Change the program to create the file once(before loop) and use it inside the loop to write it.
Also do not close the file as soon as you have written it. Use it once you encounter "stop". Close() should be used when you are done with writing into the file.
Try using flush() before close() to send all data in the buffer to the the file.
You must close you FileWriter (fw) out of while loop.
Try below code
public static void main(String[] args) throws IOException {
FileWriter fw = null;
try {
fw = new FileWriter("C:/Users/MYPC/Desktop/abcd.txt");
String str;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter your lines");
str = sc.nextLine();
if (!str.equals("stop")){
fw.write(str);
}
fw.write("\n");
} while (!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
// Logger.getLogger(FileReadLine.class.getName()).log(Level.SEVERE,
// null, ex);
}finally{
if(fw != null){
fw.close();
}
}
}
You were closing the writer in every iteration since you are not using braces in the if condition...
Try this solution, is working
try {
String str;
Scanner sc=new Scanner(System.in);
File fw = new File("C:/Users/MYPC/Desktop/abcd.txt");
FileOutputStream fos = new FileOutputStream(fw);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
do {
System.out.println("Enter your lines");
str=sc.nextLine();
if(!str.equals("stop")) {
bw.write(str);
bw.newLine();
} else {
bw.close();
}
} while(!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
}

BufferedWriter writing to console instead of text file

These are the contents of the constructor of a class which is called by the main method.
File f = null;
Scanner s;
try {
f = new File(getClass().getResource("/LOL.txt").toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
s = new Scanner(f);
while(s.hasNextLine()) System.out.println(s.nextLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(f.getAbsoluteFile(), false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("LOL");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Output in the console:
LOL
The contents of the file remain unchanged even after repeated runs. My IDE is eclipse
You parametrize your FileWriter with boolean append set as false.
Therefore, the same file will be written over every time that given constructor is executed, and "LOL" will be printed in it.
Before printing "LOL", a Scanner reads each line and prints it, hence the LOL printed in our system out.
Also note, you probably want to declare your FileWriter and BufferedWriter out of the try block, so you can flush and close them in a finally block.
This post only contains the initial question, as-is with everything corrected to avoid several resource-related bugs. It assumes Java 6 or lower.
I shouldn't get any upvote so please don't ;)
package so39452286;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
File file = new File(getClass().getResource("/LOL.txt").toURI());
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
if (scanner != null) {
scanner.close();
}
}
Writer writer = null; // Holds the main resource, not the wrapping ones.
try {
writer = new FileWriter(file.getAbsolutePath(), false);
BufferedWriter bw = new BufferedWriter(writer);
bw.write("LOL");
bw.flush(); // You forgot to flush. Ok, close() does it, but it's always better to be explicit about it.
} finally {
if (writer != null) {
writer.close();
}
}
} catch (Exception e) {
// Do something with e.
e.printStackTrace(System.err);
}
}
}

Deleting file contents android

I need to delete the contents of a file, before I write more information into it. I've tried different ways, such as where I delete the content but the file stays the same size, and when I start writing in it after the deletion, a blank hole appears to be the size of the deletion before my new data is written.
This is what I've tried...
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(path));
bw.write("");
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
And I've also tried this...
File f = new File(file);
FileWriter fw;
try {
fw = new FileWriter(f,false);
fw.write("");
}
catch (IOException e) {
e.printStackTrace();
}
Can someone please help me with a solution to this problem.
FileWriter (path, false)
The false will tell the writer to truncate the file instead of appending to it.
Try calling flush() before calling close().
FileWriter writer = null;
try {
writer = ... // initialize a writer
writer.write("");
writer.flush(); // flush the stream
} catch (IOException e) {
// do something with exception
} finally {
if (writer != null) {
writer.close();
}
}
It might be because you are not closing the FileWriter, fw.close(); also you dont need to "delete" the old data, just start writing and it will overwrite the old data. So make sure you are closing everywhere.
This works for me:
File f=new File(file);
FileWriter fw;
try {
fw = new FileWriter(f);
fw.write("");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}

Categories