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);
Related
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.
I have a function that creates a file, but when I check the created file, its contents are not in utf-8, which causes problems with the contents in latin languages.
I thought that indicating the media type as html would be enough to keep formatting, but it did not work.
File file = new File("name of file");
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
writer.write(contents);
writer.flush();
writer.close();
MultipartFile multipartFileToSend = new MockMultipartFile("file", "name of file", MediaType.TEXT_HTML_VALUE, Files.readAllBytes(Paths.get(file.getPath())));
} catch (IOException e) {
e.printStackTrace();
}
I'd like to know how to force this, because so far I have not figured out how.
Any tips?
Instead of using FileWriter, create a FileOutputStream. You can then wrap this in an OutputStreamWriter, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:
try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream("your_file_name"), StandardCharsets.UTF_8))
// do stuff
}
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.
Here is my Java code.
File file = new File(path);
StringWriter sw = new StringWriter();
//Do something.
out.println(sw.toString()); //Works fine; prints.
try {
FileUtils.writeStringToFile(file, sw.toString(), "UTF-8");
} catch (IOException e) {
throw new RuntimeException( e );
}
I don't already have the file created, and neither is it creating it after the execution.
How can I do this?
See File.createNewFile().
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. ..
As mentioned by #JohnWatts in comments:
..both PrintWriter and your code create the file, but pre-1.3 FileUtils.writeStringToFile does not.
Don't use StringWriter, use PrintWriter instead:
PrintWriter w = new PrintWriter(file);
w.print(string);
w.flush();
w.close()
I checked the code and it works.
The only problem that I could think of is path value. Try with hardcoded path value. Because I doubt file is getting created and you are not able to find it.