Write Java String to file with special encoding - java

I have got the Java String ôð¤ Ø$î1<¨ V¸dPžÐ ÀH#ˆàÀༀ#~€4` which I would like to write to a file with ANSI encoding.
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output),"windows-1252"));
try {
out.append(str);
} finally {
out.close();
}
Debugger says that str contains ôð¤ Ø$î1<¨ V¸dPÐ ÀH#àÀà¼#~4. As soon as I write it to the output file, the file only contains ?ÒÜ#4. So whats wrong with my method writing to the File?
Sorry for this weird strings - I am trying to rewrite a delphi 7 function in java. These strings are the only samples I have got.

If I run
String text = "ôð¤ Ø$î1<¨ V¸dPžÐ ÀH#ˆàÀༀ#`~€4";
Writer writer = new OutputStreamWriter(new FileOutputStream("test.txt"), "windows-1252");
writer.append(text);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt"), "windows-1252"));
String line = br.readLine();
br.close();
System.out.println(line.length() + ": '" + line + "' matches " + line.equals(text));
it prints
32: 'ôð¤ Ø$î1<¨ V¸dPžÐ ÀH#ˆàÀༀ#`~€4' matches true
so no characters are lost in translation.
If I change the encoding to "US-ASCII" I get the following output
32: '??? ?$?1<? V?dP?? ?H#??????#`~?4' matches false

Related

Remove line of Text and Rewrite File

Here is my code. Everything works except the last two lines. I am trying to remove a line from a .txt and rewrite the file into a tempfile and then rename the tempfile to original. The last two lines are being ignored though. Here is what the error is:
https://i.gyazo.com/66a320aeaf487837ce64fe3424074de6.png
These two lines are being ignored:
inputFile.delete();
tempFile.renameTo(inputFile);
File inputFile = new File(a.getDirectoryData() + "UserTwo.txt");
File tempFile = new File(a.getDirectoryData() + "TempUserTwo.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(a.username + ":" + a.password)) continue;
writer.write(currentLine + "\r\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
Looks like it cannot delete a file. Can you try to use
Files.delete(inputFile.toPath())
instead?
From docs:
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

Java: BufferdWriter prints String into two lines for no reason?

I am currently writing a "text check" program in Java, but somehow I got stuck whilst creating an unique identifier for every file.
Actually I create an new identifier like this:
String identifier = Base64.encode((dateFormat.format(date) + "#" + uuid.toString() + "#" + name+".sc0").getBytes()).replace("=", "");
Also my program creates a new file and opens a BufferedWriter.
Actually when I now try to append (I tried using BufferedWriter#write, too, but it didn't work either.)
If I write this String into the file now, it looks like this:
BlMjAxNi8wMy8zMSAyMDo0MjowOSMzMThhYjRkNS0yNjFhLTQwNjItODkyOS03NzlkZDIyOWY4Nj
dGVzdC5zYzA
but it should be in only one line like this:
BlMjAxNi8wMy8zMSAyMDo0MjowOSMzMThhYjRkNS0yNjFhLTQwNjItODkyOS03NzlkZDIyOWY4NjdGVzdC5zYzA
At first I thought that it would probably have a problem with me creating a new line after using BufferedWriter#write, so I tried flushing my BufferedWriter before creating a new line. It didn't work either...
PS:
The whole neccessary code:
String name = file.getName().substring(0, ind);
File next = new File(folder.getAbsolutePath(), name+".sc0");
String identifier = Base64.encode((dateFormat.format(date) + "#" + uuid.toString() + "#" + name+".sc0").getBytes()).replace("=", "");
try {
next.delete();
next.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(next));
logger.info("Adding compiler identifier to file ...");
writer.write("#Script0:"+identifier);
writer.flush();
writer.newLine();
for(String str : lines) {
writer.newLine();
writer.append(str);
}
writer.flush();
writer.close();
} catch (IOException e) {
logger.error("Strange bug ... Did you delete the file? Please try again!");
return;
}
It's the encoder, not the BufferedWriter. Base-64 encoding uses a line length of (I believe) 72 characters.

How to add a new line after writing a array of characters into a file using JAVA

After executing the following piece of code
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fileOutputStream.write(content.getBytes());
}
catch (IOException e) {
e.printStackTrace();
}
output is as follows:.
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to DrawerCONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)CONSOLIDATED_UNPAID_code_66 _KE = Wrong/Missing Reference
but i want it like
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to Drawer
CONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)
Pls suggest
I'd have to see the rest of the code to tell you exactly what you should do, but you can simply use the character "\n" in your string.
You can achieve adding new line to a file in quite a few ways, here is the two approaches:
Add a \n to your String which would cause the remainder of the string to be printed in new line
Use PrintWriter's println method to print each string in new line
Also keep in mind that opening a file with Notepad might not recognize \n hence do not display the remainder of string in new line, try opening the file using Notepadd++
String code2 = "code12";
String countryCode2 = "countryCode2";
String reason2 = " \n I am reason.";
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fout.write(content.getBytes());
//don't forget to flush the output stream
fout.flush();
} catch (IOException e) {
e.printStackTrace();
}
Use PrintWriter as shown below:
String line1 = "This is line 1.";
String line2 = "This is line 2.";
File f = new File("C:\\test_stackoverflow\\test2.txt");
PrintWriter out = new PrintWriter(f);
out.println(line1);
out.println(line2);
//close the output stream
out.close();
First, use a Writer on top of the output stream to write strings to files. This way, you'll be in control of the output character encoding.
Second, if you want to use your platform's line separator, you may use PrintWriter which has println() methods using the correct newline character or character sequence.
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(fileOutputStream, OUTPUT_ENCODING)
);
...
writer.println(content);
Found solution for this . Appending /n wouldnt solve any issue rather use BufferedWriter. BufferedWriter has a inbuilt newline mwthod to do the same. Thanks
Solution:
try {
File file = new File("Danny.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutputStream) );
String content = new String("CONSOLIDATED_UNPAID_description_"+code2+"_"+countryCode2+" = "+description2);
bw.write(content);
bw.newLine();
bw.flush();
check = true;
}
catch (IOException e) {
e.printStackTrace();
}

Reading in pound sign and speech marks

I am currently reading in a file into java where the file contains list of ("char symbol" "tab" "6 comma seperated booleans" "new line")
I am reading it in fine and splitting it up ok - however i have a problem whereby the pound sign and speech marks are being read in as a black diamond with a question mark in it. This is screwing everything up as i need to be able to identify which codes go with which char symbol.
I am reading in using:
public void read()
{
int i = 0;
try{
// Open the file
InputStream is = am.open("combinations.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(is);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null && i < 53) {
String[] sep1 = strLine.split("\t");
String[] sep2 = sep1[1].split(",");
entries[i] = new Entry(sep1[0].charAt(0), new CellPattern(Boolean.valueOf(sep2[0]),
Boolean.valueOf(sep2[1]),Boolean.valueOf(sep2[2]),Boolean.valueOf(sep2[3]),
Boolean.valueOf(sep2[4]),Boolean.valueOf(sep2[5])));
i++;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
It is an encoding problem, try changing your BufferedReader line to:
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
I'm not sure which encoding you'll need, so you may want to try a few different ones.
Edit:
Try "ISO-8859-1"

Read XML, Replace Text and Write to same XML file via Java

Currently I am trying something very simple. I am looking through an XML document for a certain phrase upon which I try to replace it. The problem I am having is that when I read the lines I store each line into a StringBuffer. When I write the it to a document everything is written on a single line.
Here my code:
File xmlFile = new File("abc.xml")
BufferedReader br = new BufferedReader(new FileReade(xmlFile));
String line = null;
while((line = br.readLine())!= null)
{
if(line.indexOf("abc") != -1)
{
line = line.replaceAll("abc","xyz");
}
sb.append(line);
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(xmlFile));
bw.write(sb.toString());
bw.close();
I am assuming I need a new line character when I prefer sb.append but unfortunately I don't know which character to use as "\n" does not work.
Thanks in advance!
P.S. I figured there must be a way to use Xalan to format the XML file after I write to it or something. Not sure how to do that though.
The readline reads everything between the newline characters so when you write back out, obviously the newline characters are missing. These characters depend on the OS: windows uses two characters to do a newline, unix uses one for example. To be OS agnostic, retrieve the system property "line.separator":
String newline = System.getProperty("line.separator");
and append it to your stringbuffer:
sb.append(line).append(newline);
Modified as suggested by Brel, your text-substituting approach should work, and it will work well enough for simple applications.
If things start to get a little hairier, and you end up wanting to select elements based on their position in the XML structure, and if you need to be sure to change element text but not tag text (think <abc>abc</abc>), then you'll want to call in in the cavalry and process the XML with an XML parser.
Essentially you read in a Document using a DocuemntBuilder, you hop around the document's nodes doing whatever you need to, and then ask the Document to write itself back to file. Or do you ask the parser? Anyway, most XML parsers have a handful of options that let you format the XML output: You can specify indentation (or not) and maybe newlines for every opening tag, that kinda thing, to make your XML look pretty.
Sb would be the StringBuffer object, which has not been instantiated in this example. This can added before the while loop:
StringBuffer sb = new StringBuffer();
Scanner scan = new Scanner(System.in);
String filePath = scan.next();
String oldString = "old_string";
String newString = "new_string";
String oldContent = "";
BufferedReader br = null;
FileWriter writer = null;
File xmlFile = new File(filePath);
try {
br = new BufferedReader(new FileReader(xmlFile));
String line = br.readLine();
while (line != null) {
oldContent = oldContent + line + System.lineSeparator();
line = br.readLine();
}
String newContent = oldContent.replaceAll(oldString, newString);
writer = new FileWriter(xmlFile);
writer.write(newContent);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
scan.close();
br.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories