How to write special characters to a text file - java

This is my code, I am trying to write a text file replacing "Up" and "Right" with ↑ and →. The problem is that the text file output is: "→ ↑"(this is not what i wanted) and the console output is "↑ →".
private static void print(String t){
File log = new File("a.txt");
String raw = t;
raw = raw.replaceAll("Up", " \u2191 "); //↑
raw = raw.replaceAll("Right", " \u2192 "); //→
try{
FileWriter fileWriter = new FileWriter(log, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(raw + "\n");
System.out.println(raw + "\n")
bufferedWriter.close();
}catch(IOException e) {}
}
I think it may be an encoding error, but I dont know how to fix it.

First of all, it's best to specify the encoding (you probably want UTF-8) before you write your file.
private static void print(String t){
File log = new File("a.txt");
String raw = t;
raw = raw.replaceAll("Up", " \u2191 ");
raw = raw.replaceAll("Right", " \u2192 ");
try{
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(log), "UTF-8"));
bufferedWriter.write(raw + "\n");
System.out.println(raw + "\n");
bufferedWriter.close();
}catch(IOException e) {}
}
Then, you need to make sure that your file viewer is also set to UTF-8. It seems that your file viewer might be viewing the file in ANSI instead. Changing that setting would depend on your file viewer -- try Googling "[your file viewer name] UTF-8".

Related

Java: Bank simulation: Write to file, erased text/writing symbols

As a way to learn java, I attempted to write something simulating a bank(adding or removing numbers). I succeeded in creating a file(if one does not exist already), and then read from it, but when I attempt to write to it, it fails. I started with FileWriter, where it just erased the text in the document(balance.txt). I then tried BufferedWriter, and it wrote to the document, but it was just symbols instead of actual text/numbers. I'm aware that I'm a newbie when it comes to coding, but is there a solution to this? Thank you.
if (choice.equals("ADD")){
System.out.println("Currently selected: " + choice);
//write to file
try {
String filePath = "C:\\Users\\user\\Desktop\\programming\\projects\\java\\RandomStuff\\Bank\\balance.txt";
// System.out.println("How much would you like to add?");
// Scanner inputAdd = new Scanner(System.in);
// String balanceToAdd = inputAdd.nextLine();
// writeToFile.write(balanceToAdd);
int balanceToAdd = 1;
BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
out.write(balanceToAdd);
out.close();
System.out.println("Added: " + balanceToAdd);
} //try end
catch(IOException e){
System.out.println("Error(line56): " + e.getMessage());
}
public FileWriter(String fileName,
boolean append)
I think you should use append to edit your file.
BufferedWriter out = new BufferedWriter(new FileWriter(filePath,true));

FileReaders readLine return always null JAVA

Writing a program in java I'm trying to read the content of a file which is treated as a storage. I have a function to modify the amount of an object in the store, which is organized with one line per product, where the first word is the prodCode, and the second is the amount of it.
This is the function:
public static void modifyAmount(String prodCode, String newAmount){
try{
File magazzino = new File("Magazzino.txt");
BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
FileWriter toFile = new FileWriter(magazzino);
String oldContent="";
String line;
String lineToReplace = prodCode + " " + amountRequest(prodCode);
String newLine = prodCode + " " + newAmount;
while((line = fromFile.readLine()) != null){
oldContent = oldContent + line + "\n";
System.out.println("leggendo " + line);
}
System.out.println(oldContent);
String newContent = oldContent.replaceAll(lineToReplace, newLine);
toFile.write(newContent);
toFile.close();
fromFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
And the result of it is that it won't enter the while cycle because the first readLine result null, though the file is correctly formatted, the 'amountRequest' function works properly and the input is correct.
Magazzino.txt:
1 12
3 25
4 12
You're probably having trouble because you're trying to read and write the file at the same time, with different file handles. I'd suggest reading the file first, then closing the FileReader, then creating a FileWriter to write to it.
The issue is that before you have read the contents of the file, you are creating an instance of FileWriter which will clear the file.
FileWriter toFile = new FileWriter("Magazzino.txt"); will clear the file
The solution is to just create the instance of FileWriter after you are done reading the file.
public static void modifyAmount(String prodCode, String newAmount){
try{
File magazzino = new File("Magazzino.txt");
BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
String oldContent="";
String line;
String lineToReplace = prodCode + " " + amountRequest(prodCode);
String newLine = prodCode + " " + newAmount;
while((line = fromFile.readLine()) != null){
oldContent = oldContent + line + "\n";
System.out.println("leggendo " + line);
}
fromFile.close();
System.out.println(oldContent);
String newContent = oldContent.replaceAll(lineToReplace, newLine);
FileWriter toFile = new FileWriter(magazzino);
toFile.write(newContent);
toFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
You open a file twice, simultaneously for reading and writing.
As soon as you do this line,
FileWriter toFile = new FileWriter(magazzino);
your file is erased. Check it yourself.
Actually, with this line you are creating a new empty file for writing instead of the old one.
I'd suggest read file, then close, then write.
You can also try to pen file for append : new FileWriter("filename.txt", true);
This will not erase old file, allowing you to read it. But the new data will be appended to the end, though.
If you want to use you file as a state or storage, I'd suggest to look at sqlite: https://www.sqlite.org/index.html

StringEscapeUtils.unescapeHtml doesn't work on strings read from files

I'm trying to read in a file that contains unicode characters, convert those characters to their corresponding symbols and then print the resulting text to a new file. I'm trying to use StringEscapeUtils.unescapeHtml to do this but the lines are just being printed as is, with the unicode points still intact. I did a practice run by copying a single line from the file, making a string from that and then calling StringEscapeUtils.unescapeHtml on that, which works perfectly. My code is below:
class FileWrite
{
public static void main(String args[])
{
try{
String testString = " \"text\":\"Dude With Knit Hat At Party Calls Beer \u2018Libations\u2019 http://t.co/rop8NSnRFu\" ";
FileReader instream = new FileReader("Home Timeline.txt");
BufferedReader b = new BufferedReader(instream);
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(StringEscapeUtils.unescapeHtml3(testString) + "\n");//This gives the desired output,
//with unicode points converted
String line = b.readLine().toString();
while(line != null){
out.write(StringEscapeUtils.unescapeHtml3(line) + "\n");
line = b.readLine();
}
//Close the output streams
b.close();
out.close();
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
//This gives the desired output,
//with unicode points converted
out.write(StringEscapeUtils.unescapeHtml3(testString) + "\n");
You are mistaken. Java unescapes String literals of this form at compile time when it builds them into the class file:
"\u2018Libations\u2019"
There are no HTML 3 escapes in this code. The method you have chosen is designed to unescape escape sequences of the form ‘.
You probably want the unescapeJava method.
You're strings are being both read and written using your platforms default encoding. You want to explicitly specify the character set to use as 'UTF-8':
Input stream:
BufferedReader b = new BufferedReader(new InputStreamReader(
new FileInputStream("Home Timeline.txt"),
Charset.forName("UTF-8")));
Output stream:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("out.txt"),
Charset.forName("UTF-8")));

java : append data in existing file

i have a file DataFile.txt with few records. when i am adding new entry, it clears all the other records and saving only new one. but i want to append that record.
private void saveFile()
{
try
{
PrintWriter out = new PrintWriter(new FileWriter("DataFile.txt"));
String name ="";
String ID="";
String roomType ="";
String meal="";
int days=0;
int tprice=0;
for (int i = 0; i < myList.size(); i++)
{
Customer c = myList.get(i);
name = c.getName();
ID = c.getID();
roomType = c.getRoomItem();
meal = c.getMealItem();
days = c.getDaysIndex();
tprice = c.getTotalPrice();
out.println(name + "," + ID+ "," + roomType+ "," + meal+ "," + days+ "," + tprice);
}
out.close();
JOptionPane.showMessageDialog(null,"Data saved successfully!","",
JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
System.out.println("save file fail");
}
} //end of the method
thanks.
You can change to use the FileWriter constructor which takes a boolean append parameter:
PrintWriter out = new PrintWriter(new FileWriter("DataFile.txt", true));
However:
PrintWriter swallows exceptions - I wouldn't use it if I were you
FileWriter always uses the platform default encoding - I wouldn't use that, either. I'd use an OutputStream wrapped in an OutputStreamWriter created with a specific encoding.
Do not use FileWriter. It is not possible to define character encoding with FileWriter aand you will end up using system default encoding, which usually will not be what you want to use.
Instead use FileOutputStream and an OutputStreamWriter. Yes, it is an extra line of code, but that extra line is required if you want to write robust and bug free code.
OutputStream out = new FileOutputStream("output.txt", true);
Writer writer = new OutputStreamWriter(out, "UTF-8");
Using system default character encoding is the most common source for bugs. Make a habit of learning to not rely on system default character encoding (or system default time zone).

Java save multiline string to text file

I am new to Java and trying to save a multi line string to a text file.
Right now, it does work within my application. Like, if I save the file from my application and then open it from my application, it does put a space between lines. However, if I save the file from my app and then open it in Notepad, it is all on one line.
Is there a way to make it show multi line on all programs? Here's my current code:
public static void saveFile(String contents) {
// Get where the person wants to save the file
JFileChooser fc = new JFileChooser();
int rval = fc.showSaveDialog(fc);
if(rval == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
//File out_file = new File(file);
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(contents);
out.flush();
out.close();
} catch(IOException e) {
messageUtilities.errorMessage("There was an error saving your file. IOException was thrown.", "File Error");
}
}
else {
// Do nothing
System.out.println("The user choose not to save anything");
}
}
depending on how you are constructing your string, you may just be running into a line ending problem. Notepad does not support unix line endings (\n only) it only supports windows line endings (\n\r). try opening your saved file using a more robust editor, and/or make sure you are using the proper line endings for your platform. java's system property (System.getProperty("line.separator")) will get you the proper line ending for the platform that the code is running on.
while you're building your string to be saved to the file, rather than explicitly specifying "\n" or "\n\r" (or on the mac "\r") for your line endings, you would instead append the value of that system property.
like so:
String eol = System.getProperty("line.separator");
... somewhere else in your code ...
String texttosave = "Here is a line of text." + eol;
... more code.. optionally adding lines of text .....
// call your save file method
saveFile(texttosave);
Yea as the previous answer mentions the System.getProperty("line.seperator").
your code doesn't show how you created String contents but since you said you were new to java I thought i'd mention that in java concatenating Strings is not nice since it creates a. If you are building the String by doing this:
String contents = ""
contents = contents + "sometext" + "some more text\n"
Then consider using java.lang.StrinBuilder instead
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("sometext").append("somre more text\n");
...
String contents = strBuilder.toString();
Another alternative is to stream what ever your planning to write to a file rather than building a large string and then outputting that.
You could add something like:
contents = contents.replaceAll("\\n","\\n\\r");
if notepad does not display correctly. However you might run into a different problem: at each save/load you will get multiple \r chars. Then to avoid that at load you would have to call the same code above but with reversed parameters. This is really an ugly solution just to get the text to display properly in notepad.
I had this same problem my guy friend, after much thought and research I even found a solution.
You can use the ArrayList to put all the contents of the TextArea for exemple, and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file.
if something does not make sense, I'm sorry is google translator and I who do not speak English.
Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();
Text.add(TextArea.getText());
SaveFile(NameFile, Text);
}
public void SaveFile(String name, ArrayList< String> message) {
path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";
File file1 = new File(path);
try {
if (!file1.exists()) {
file1.createNewFile();
}
File[] files = file1.listFiles();
FileWriter fw = new FileWriter(file1, true);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < message.size(); i++) {
bw.write(message.get(i));
bw.newLine();
}
bw.close();
fw.close();
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
fw = new FileWriter(file1, true);
bw = new BufferedWriter(fw);
while (br.ready()) {
String line = br.readLine();
System.out.println(line);
bw.write(line);
bw.newLine();
}
br.close();
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error in" + ex);
}

Categories

Resources