BufferedWriter not writing to .txt file even after flushing the writer - java

Here's the code I used, I get no errors or warnings but the file is empty, I created the aq.txt file and placed it in the workspace and it also shows in the project. I'm sure it's something stupid I'm missing but I just can't figure it out. Also, I tried all the other questions but the suggested answer is closing the stream and/or flushing it, both of which I do but they don't seem to work. Any help would be greatly appreciated!
Writer writer = null;
FileOutputStream fos= null;
try{
String xyz= "You should stop using xyz";
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(getFilesDir()+File.separator+"aq.txt")));
writer.write(xyz);
writer.flush();
}
catch(IOException e) {
System.out.println("Couldn't write to the file: " + e.toString());
}
finally{
if(writer != null){
try {
writer.close();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
}

Try like this:
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(xyz);
writer.flush();
Context class provides a helper method Context.openFileOutput(String name, int mode) that will return a FileOutputStream to you for a file located in your applications Files directory.
I don't see any immediate reason why your way would not work, but I know I've used this other way successfully.
EDIT: After re-reading your question I think you are confused about where this file is going to be written to. It will not get written to the project folder inside of your workspace. This is going to be written to the internal storage of the android device that you run it on. Every application gets its own chunk of storage space located at \data\data\[package-name]\Files\ Your file is going to get written to there so you won't be able to immediately open it up and see the contents of it (unless your device is rooted.) You will instead have to open it up with java code and print its contents to the Log or some other output method in order to verify that your write did/did not work.
EDIT 2: Reading the file
FileInputStream in = openFileInput(FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStreamReader);
String line = br.readLine();
Log.d("TAG", line);
This will read and output to the log the first line of the file.

This will certainly work :
File file = new File("fileName");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("data to write in the file.");
writer.flush();

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

How to copy image in java using bufferedreader/writer

File file = new File("download.png");
File newfile = new File("D:\\Java.png");
BufferedReader br=null;
BufferedWriter bw=null;
try {
FileReader fr = new FileReader(file);
FileWriter fw = new FileWriter(newfile);
br = new BufferedReader(fr);
bw = new BufferedWriter(fw);
char[] buf = new char[1024];
int bytesRead;
while ((bytesRead = br.read(buf)) > 0) {
bw.write(buf, 0, bytesRead);
}
bw.flush();
}
catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Whats wrong with this code. Is it possible with BufferedReader and Writer Class??
I know how to to make copy of image using InputStream and OutputStream, So don't paste solution using that!!
Whats wrong with this code.
You're using text-based classes for binary data.
Is it possible with BufferedReader and Writer Class?
Not while you're dealing with binary data, no.
I know how to to make copy of image using InputStream and OutputStream, So don't paste solution using that!
That's the solution you should use, because those are the classes designed for binary data.
Fundamentally, using Reader or Writer for non-text data is broken, and asking for trouble. If you open up the file in a text editor and don't see text, it's not a text file... (Alternatively, it could be a text file that you're using the wrong encoding for, but things like images and sound aren't naturally text.)
Use javax.imageio.ImageIO utility class, which has lots of utility method related to images processing.
try{
File imagefile = new File("download.png");
BufferedImage image = ImageIO.read(imagefile);
ImageIO.write(image, "png",new File("D:\\Java.png"));
.....
}

Read directly from a URL and write in a file - Java [duplicate]

This question already has answers here:
How can I download and save a file from the Internet using Java?
(23 answers)
Closed 7 years ago.
I am reading the contents of a URL and write a file the problem is that I'm not able to write all the content in the file and do not know what I'm doing wrong.
My code,
try {
URL url = new URL(sourceUri);
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
file.getParentFile().mkdirs();
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
while ((inputLine = br.readLine()) != null) {
bw.write(inputLine + System.getProperty("line.separator"));
}
br.close();
System.out.println("DONE");
}catch (IOException ioe){
ioe.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
return ontologies;
}
Please help
You are doing many things incorrectly.
First: you don't close all your resources; where is the writer to the file closed?
Second: you use new InputStreamReader(...) without specifying the encoding. What says that the encoding on the other end is the one of your JVM/OS combination?
Last but not least, and in fact, this is the most important, you should use java.nio.file. This is 2015 after all.
Simple solution:
final Path path = file.toPath(); // or rather use Path directly
Files.createDirectories(path.getParent());
try (
final InputStream in = conn.getInputStream();
) {
Files.copy(in, path);
}
Done, encoding independent, and all resources closed.
The problem is you're using a BufferedWriter and you don't close it. It has some content in his buffer that is not writing and you're missing.
Try flushing the buffer and closing the BufferedWriter:
bw.flush();
bw.close();
Include this two lines after before your br.close();.
Also you can read how BufferedWriter works here.
And I think you should close FileWriter, too, in order to unblock the file.
fw.close();
EDIT 1:
Closing the BufferedWriter will flush the buffer for you. You need only to close it.

Java File Output Check

I have just written a long amount of code and I am trying to write an output file with this code-
File outfile = new File ("output.txt");
PrintWriter outFile = new PrintWriter(outfile);
outFile.printf("%-20s%5s%5s%5s%5s", f,median,avg,min,max);
outFile.println("");
outFile.printf("%-20s%5s%5s%5s%5s", f,median,avg,min,max);
outFile.println("");
outFile.printf("%-27s%5d%5d%5d%5d", firstplayer,P1median,P1avg,PScore.get(0),PScore.get(PScore.size()-1));
outFile.println("");
outFile.printf("%-27s%5d%5d%5d%5d", secondplayer,P2median,P2avg,Player2.get(0),Player2.get(Player2.size()-1));
outFile.println("");
outFile.printf("%-27s%5d%5d%5d%5d",fourthplayer,P4median,P4avg,Player4.get(0),Player4.get(Player4.size()-1));
outFile.close();
Now as I had no errors or exceptions thrown I believe I have succeed in writing an output file, however I have no idea where it is located and how I can check the content of it. I apologize if this is a bad question but I was struggling to find an answer elsewhere, so any help locating the output file or correcting my mistakes would be appreciated greatly.
This will print out the full file path if you're still unsure where it's located:
System.out.println(outfile.getAbsolutePath());
If you want to print out the contents of the file so you can examine it in your program:
//ensure content in file is updated
outfile.flush();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(outfile));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
Make sure to close the file as well.
You should close your file to ensure everything is good.
outFile.close();
You can also flush from time to time if you want those results to appear on disk as you go.
outFile.flush();
Also, you shouldn't name two variables the same except for case. Call your File, file, and your PrintWriter, writer.
I've read from the book of "Core Java", and here is another way to find your file directory,
String dir=System.getProperty("user.dir");
System.out.println(dir);
and through the directory of the console,you may find your file "output.txt"

How to add content to files using Java

I have a result being entered into a file. This result is being done on a loop. So, every time a new result comes, it has to be appended into a file, but it is being overwritten. What should I use in order to append my results into a single file?
Try
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("filename", true));
out.write("aString");
}
catch (IOException e) {
// handle exception
}
finally{
if(out != null){
try{
out.close();
}
catch(IOException e){
// handle exception
}
}
}
According to the API,
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.
here is the basic snippet
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java 1");
out.write("Hello Java 2");
See Also
FileWritter - Javadoc
You should either keep the file open (sometimes it better, but usually not...) or open the output stream in append mode:
OutputStream os = new FileOutputStream(file, true);

Categories

Resources