Write Velocity file forced in UTF-8 - java

I'm using the following code to output a Velocity template to a file :
FileWriter fileWriterOut = new FileWriter(outFile);
logger.debug("encoding " + fileWriterOut.getEncoding());
fileWriterOut.write(template.getStringWriter().toString());
fileWriterOut.close();
Problem is :
Deployed in a non UTF-8 App Server, outFile is written using default encoding (iso-xxxx).
You can verify it with fileWriterOut.getEncoding()
It seems that no method in FileWriter class could set another encoding.
How can I force UTF-8 when writing my file ?

Use a FileOutputStream in combination with an OutputStreamWriter:
final OutputStream out = new FileOutputStream(...);
final Writer writer
= new OutputStreamWriter(out, Charset.forName("UTF-8"));

I've found a way to do this, I'm not sure that's the most convenient one, but it works correctly.
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
out.write(template.getStringWriter().toString());
}
catch ...
finally
{
try {
out.close();
} catch...
}

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 force content from a file to be utf-8 in java spring?

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
}

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

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

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();

Read and write to file, but overwrites the file

I'm trying to figure out why this doesn't work. All the files which are shown actually exist. The 'logging.toString()' is a .txt file and it reads all the text in the logging and writes it back with the String which I want to be added. Although when I do this, it overwrites it. But I dont want that. Help?
try{
FileWriter fstream = new FileWriter(logging.toString());
BufferedWriter out = new BufferedWriter(fstream);
FileInputStream fstreams = new FileInputStream(logging);
BufferedReader br = new BufferedReader(new InputStreamReader(fstreams));
String strLine;
while ((strLine = br.readLine()) != null){
htmlTextArea = htmlTextArea + strLine + "\n";
}
out.write(htmlTextArea + logto);
out.close();
} catch (Exception ex){}
Why wouldn't it? You don't pass an append flag:
FileWriter(String filename, boolean append)
The API docs are your friend; they're often helpful for understanding behavior.
Change this line
FileWriter fstream = new FileWriter(logging.toString());
to
FileWriter fstream = new FileWriter(logging.toString(), true);
That way, you tell Java you wish to APPEND the file. There's more in the Javadocs for FileWriter.
Because that's the way FileWriter is implemented.
If you want to append, you should use a different constructor: new FileWriter( logging.toString(), true );
If you want to add something to file but not overwrite it use
FileWriter fstream = new FileWriter(logging.toString(),true);

Categories

Resources