What is wrong in the below code? in console it is printing proper data but in file there is no data. it is creating 0-byte file.
JsonObjectBuilder mainObj= Json.createObjectBuilder();
mainObj.add("delete",delete);
mainObj.add("update", update);
mainObj.add("add",add);
String data = mainObj.build().toString();
System.out.println(data); **//This line printing output**
BufferedWriter out = new BufferedWriter(new FileWriter("D:/test.json"));
out.write(data);
Below output is getting printed to console but it is creating 0-byte file.
{"delete":[{"canonicalName":"Amazon"}],"update":[{"canonicalName":"Infosys"},{"canonicalName":"Google HYD"}],"add":[{"canonicalName":"Apple computers"},{"canonicalName":"Microsoft India"},{"canonicalName":"Amazon"},{"canonicalName":"Google India"},{"canonicalName":"CSC"},{"canonicalName":"INFY"}]}
As mentioned in the comments you forgot to close the writer.
Instead of out.close() you can also use the new syntax try-with-resources since Java 7:
try (BufferedWriter out = new BufferedWriter(new FileWriter("D:/test.json"))) {
out.write(data);
}
This will automatically close all Closeables at the end of the try block.
Attention: the FileWriter will not be closed by the try-with-resource mechanism as there is no variable created for the FileWriter. Luckily the BufferedWriter.close() will also close the passed FileWriter.
Related
There are so many Input/Output Classes in Java.
It is really a mess. You do not know which to use.
Which functions does operating system offer ? There will be one
to read one byte of a file or many bytes of a file I guess.
So for example if I use this.
String path = "C:\\Users\\myName\\test.txt";
FileOutputStream fos = new FileOutputStream(path);
fos.write(333);
If I open it with a text editor it shows me letter "G" . Already I do not understand this.
And this code does not write anything, the file is empty weirdly.
String path = "C:\\Users\\myName\\test.txt";
FileOutputStream fos = new FileOutputStream(path);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
out.write("something");
All these I/O classes just confuse me. What does buffered mean. It reads 1000 Bytes at once. So
there is operating function to straight away read 1000 Bytes of a file I guess.
You need to close the instances of BufferedWriter out and FileOutputStream fos, after invoking the out.write("something"), then only the file gets created successfully with the contents you are trying to write.
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\myName\\test.txt";
FileOutputStream fos = new FileOutputStream(path);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
out.write("something");
out.close(); // Closes the stream, flushing it first.
fos.close(); // Closes this file output stream and releases any system resources associated with this stream.
}
Closing the instances of BufferedWriter and FileOutputStream will solve the issue.
fos.write(333) => The number has been written to the file and when you open the file it opens in ASCII format. You can use below code.
public static void main(String[] args) throws IOException {
FileWriter fw=new FileWriter("D:\\test.txt");
fw.write("Hello! This is a sample text");
System.out.println("Writing successful");
fw.close();
/* your code
String path = "D:\\test1.txt";
FileOutputStream fos = new FileOutputStream(path);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
out.write("Hello! This is a sample text");
out.close();
fos.close();
*/
}
There are so many Input/Output Classes in Java. It is really a mess. You do not know which to use.
The Files class is by far the easiest to use. For instance,
Files.writeString(Paths.get("test.txt"), "hello world!");
creates a text file named "test.txt" containing the text "hello world!".
The other classes are only needed if you want to do something fancy (for instance, deal with files too big to fit in main memory). For instance, suppose you wanted to read a huge log file (hundreds of gigabytes long) and wanted to write each line containing a particular word to another file. If you were to open the file with
Files.readAllLines(Paths.get("huge.log"));
you'd receive an OutOfMemoryError because the file doesn't fit in main memory. To work around that, we must read the file piece-wise, and that is what all those Reader and Writer classes (or InputStream and OutputStream, if you're dealing with binary files) are good for:
try (
var reader = Files.newBufferedReader(Paths.get("huge.log"));
var writer = Files.newBufferedWriter(Paths.get("interesting.log"));
) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchWord)) {
writer.write(line);
writer.write('\n');
}
}
}
As you can see, their use is quite a bit more complicated. For one, we must close the Reader and Writer once we are done with them, which is easiest accomplished with the try with resources statement shown above.
Closing is necessary because most operating systems limit the number of files that can be open at once. Closing also gives any Buffered* classes the opportunity to empty their buffers, ensuring that any data still in buffers is passed on to the file system.
If we fail to close, as you did in your example code, the file remains open until our program exits, upon which time any data in the buffers is lost, resulting in the incomplete file you found.
Here is what I am working with basically (example file):
Line 1: 213124
Line 2: 243223
Line 3: 325425
Line 4: 493258
Line 5: 359823
Is there a way to make PrintWriter begin to write to a file with 5 lines shown above, but so that it only writes AFTER line 5? So like I want to use
PrintWriter log = new PrintWriter("blah.txt");
log.println("52525")
and I want it to write that to line 6, not overwrite line 1.
EDIT: For anyone with a similar problem, you want to figure out how to append your files. As of my writing this, two people showed how below
To append to an existing file use "append" mode:
FileOutputStream fos = new FileOutputStream(filename,true);
PrintWriter pw = new PrintWriter(fos);
The true argument to the FileOutputStream constructor sets append mode.
To append to a file, you need to use the FileWriter(String fileName, boolean append) constructor:
try (PrintWriter log = new PrintWriter(new FileWriter("blah.txt", true))) {
log.println("52525");
}
If you're going to write a lot of output, then a BufferedWriter may be good, and if you need to specify the character encoding, you need to wrap a FileOutputStream with an OutputStreamWriter. This makes the chain much longer:
try (PrintWriter log = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("blah.txt", true),
Charset.forName("UTF-8"))))) {
log.println("52525");
}
The PrintWriter(String fileName) you called is actually shorthand for:
new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileName)))
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.
Why am I getting the following exception? What I am doing is writing a giant ArrayList line by line to a file onto the disk. The file generated is about >700MB.
It seems like it has some problem when written line by line. Could the size of the file a reason? Why is the stream closed? By the way, I am working on a Windows OS.
FileWriter evaluated_result =
new FileWriter(path_output+this.algorithm+"/"+query_type+"/"+"queries.eval");
BufferedWriter out = new BufferedWriter(evaluated_result);
out.write(Myobject);
out.newLine();
evaluated_result.close();
out.close();
The exception is as follows:
java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:45)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:118)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129)
at java.io.BufferedWriter.close(BufferedWriter.java:264)
at Assignment_1.Query_Evaluator.write100BestDocumentsEvalFormat(Query_Evaluator.java:85)
at Assignment_1.Experiment.ConductExperiment(Experiment.java:54)
at Assignment_1.Main.main(Main.java:78)
You should close the BufferedWriter before closing the FileWriter.
And, the closing calls should be in a finally block. This is one way to do it (with one finally):
FileWriter evaluated_result = new FileWriter(path_output+this.algorithm+"/"+query_type+"/"+"queries.eval");
BufferedWriter out = new BufferedWriter(evaluated_result);
try {
out.write(Myobject);
out.newLine();
}
finally {
if (out != null) out.close();
if (evaluated_result != null) evaluated_result.close();
}
(Look here for more options)
Also note that, as mentioned by #oldrinb, you don't have to close nested streams. But I think it's good practice anyway.
With Java 7 you can use the try-with-resources statement.
I have a StringWriter variable, sw, which is populated by a FreeMarker template. Once I have populated the sw, how can I print it to a text file?
I have a for loop as follows:
for(2 times)
{
template.process(data, sw);
out.println(sw.toString());
}
Right now, I am just outputting to the screen only. How do I do this for a file? I imagine that with each loop, my sw will get changed, but I want the data from each loop appended together in the file.
Edit:
I tried the code below. When it runs, it does show that the file.txt has been changed, but when it reloads, the file still has nothing in it.
sw.append("CheckText");
PrintWriter out = new PrintWriter("file.txt");
out.println(sw.toString());
How about
FileWriter fw = new FileWriter("file.txt");
StringWriter sw = new StringWriter();
sw.write("some content...");
fw.write(sw.toString());
fw.close();
and also you could consider using an output stream which you can directly pass to template.process(data, os); instead of first writing to a StringWriter then to a file.
Look at the API-doc for the template.process(...) to find out if such a facility is available.
Reply 2
template.process(Object, Writer) can also take a FileWriter object, witch is a subclass of Writer, as parameter, so you probably can do something like that:
FileWriter fw = new FileWriter("file.txt");
for(2 times)
{
template.process(data, fw);
}
fw.close();
You can use many different streams to write to file.
I personally like to work with PrintWriter here
You can flag to append in the FileWriter (the true in the following example):
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println(sw.toString());
out.close();
} catch (IOException e) {
// Do something
}
Why not use a FileWriter ?
Open it before you loop and generate your required output. As you write to the FileWriter it'll append to the buffer and write out your accumulated output upon a close()
Note that you can open a FileWriter in overwrite or append mode, so you can append to existing files.
Here's a simple tutorial.
If you don't mind using Apache commons IO :
FileUtils.write(new File("file.txt"), sw.toString(), /*append:*/ true);