Java FileWriter lost special characters [duplicate] - java

This question already has answers here:
Java BufferedWriter object with utf-8
(4 answers)
Closed 7 years ago.
I've this code
//write a file in a specific directory
public static void writeFile(String comment, String outputFileName) {
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter(outputFileName,true);
writer = new BufferedWriter(fWriter);
writer.write(comment);
writer.newLine();
writer.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
But when I save the file in outputFileName, it lost every special character.
File output format is .txt
Some solution?
Thanks a lot

FileWriter uses the platform-default encoding. It's very rarely a good idea to use that class, IMO.
I would suggest you use an OutputStreamWriter specifying the encoding you want - where UTF-8 is almost always a good choice, when you have a choice.
If you're using Java 7 or higher, Files.newBufferedWriter is your friend - and with Java 8, there's an overload without a Charset parameter, in which case UTF-8 is used automatically.

Related

Java how to add new line to file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 2 years ago.
Im trying to add multiple strings to a file.
FileWriter myWriter = new FileWriter("cache.txt");
BufferedWriter bw=new BufferedWriter(myWriter);
bw.write(marker);
bw.newLine();
bw.close();
But whenever I write a new String it keeps overriding.
So I only have one string in my file.
How would I make it add a new line to the file.
Here is an example
What should happen.
file(cache.txt):
fd174d5b4bbc85295a649f9d70a4adf4
9b854017b04d62732ac00f2ee8007968
...
What happens for me
file(cache.txt):
9b854017b04d62732ac00f2ee8007968(last entry)
Because that's what BufferedWriter's .write is supposed to do.
If the file doesn't exists, create and write to it.
If the file exists, truncate (remove all content) and write to it
To append, use this:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("text");
out.close();
} catch (IOException e) {
//exception handling
}
Use the "append" flag to the FileWriter constructor:
FileWriter myWriter = new FileWriter("cache.txt", true);
Otherwise the file will be reset to the beginning each time it is opened.

How to load a preexisting PrintWriter into Java? [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Java: How to read a text file
(9 answers)
Closed 5 years ago.
I have a txt file that I want to load into Java, and I've been trying to use
PrintWriter writer = new PrintWriter(new File("location/name.txt"));
But instead of loading the existing file, it writes over the old one and creates a new blank one. How can I load the existing file into Java?
You must use a Reader instead of Writer.
There are various ways to read a text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Each class has its own purpose e.g. BufferedReader is used to buffer data for reading fast, and Scanner provides parsing ability.
Example using BufferedReader :
public class ReadFile {
public static void main(String[] args)throws Exception
{
File file = new File("C:\\location\\test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
I think this is what you want:
try(PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("location/yourFileName.txt", true)))) {
pw.println("what you want to write to the file");
pw.close();
} catch (IOException e) {
//Exception handling goes here.
}
The FileWriter constructor's second argument is what sets the append condition. Also, as stated in the comments(and pretty obvious) that you need a reader to load or input data.
You can try
File f = new File(filePathString);

bufferedwriter truncate the string [duplicate]

This question already has answers here:
How to set the buffer size on a BufferedWriter over a FileWriter
(4 answers)
Closed 7 years ago.
I write a String to a file, the string is very long, about 100K, here is my code:
public static void main(String[] args) throws IOException {
String s = "kkkk";
BufferedWriter bw = new BufferedWriter(new FileWriter("/Users/liaoliuqing/Downloads/1.txt",true),1024);
bw.write(s);
bw.flush();
bw.close();
}
when the string is short, it works well. but when the string is very long, the string will be truncate, and only some character written to the file.
what is the problem?
here is my code, and it works in many threads.
private void writeToFile(String filterName, String messageToWrite)
throws IOException {
if(!messageToWrite.contains("2015")){
LOG.warn(messageToWrite);
}
bufferWritter = getBufferWriter(filterName, messageToWrite);
bufferWritter.write(messageToWrite);
if(!messageToWrite.contains("2015")){
LOG.warn(messageToWrite);
}
bufferWritter.flush();
}
I pretty sure messageToWrite is the full string, since I log it. but just the latter part of the string is written to the file.
It works in about 10 threads.
I find the problem. when one thread is writting the file, then it is the time for another thread to run, the content of first thread will confuse with 2rd thread.
I try to incread the buffer size of the bufferwriter by
returnWriter = new BufferedWriter(new FileWriter(fileName, true),64*1024);
but it is not work. it still write just 8192(the default buffer size) to the file.
how to solve this?
You need to ensure that only a single thread can use the buffered writer at a time. A simple solution is to make the writeToFile method synchronized. Otherwise you can use some sort of locking mechanism. You can either use Object.wait/notify or use a semaphore from java.util.concurrent package.

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.

Printwriter how not to overwrite [duplicate]

This question already has answers here:
PrintWriter append method not appending
(5 answers)
Closed 9 years ago.
So I got this piece of code in my Java program;
String filename = "direct.txt";
String s = fil.getAbsolutePath();
Process p = Runtime.getRuntime().exec(s);
try
{
PrintWriter outputStream = new PrintWriter(filename);
outputStream.println(s);
outputStream.close();
}
catch (FileNotFoundException e1) {e1.printStackTrace();};
But when it writes to the file, it overwrites it when it writes something new, how can I make it so it doesn't overwrite but instead goes to the next line and prints it there?
You could make a FileWriter object and pass it as an argument when making the PrintWriter object. That way if the file already exists then it won't be overwritten, but if it does not exist then it will be created. From there you can use the PrintWriter methods as normal:
FileWriter objectName = new FileWriter("filename", true);
PrintWriter outputStream = new PrintWriter(objectName);

Categories

Resources