Writing in files without overflow - java

I have the following code:
FileWriter filewriter = null;
try { filewriter = new FileWriter("outUser.txt", true); }
catch (IOException e1) { e1.printStackTrace(); }
try {
filewriter.write(s1+"\n");
filewriter.flush();
}
catch (IOException e1) { e1.printStackTrace(); }
Its supposed to write on outUser file the s1 string and a newline. It only writes s1, the newline is not written. I also tried with a new string that equals \n and append it to s1 when written but still didn't work. Do any of you have some answers for me?

The line feed should be there, but keep in mind that different OS-es have different new line characters.
If you're out of luck you can always try BufferedWriter.newLine().

Different OS have different ways to represent newlines.
For Example,\n is used in UNIX but \r\n is used in Windows.
This answers why windows uses \r
You can use System.lineSeparator() which returns the system-dependent line separator string.

Open your outUser.txt with an text editor like notepad++ and enable the 'non-printable'-chars. You should see an CR/LF, which is the \n.

The following should work
FileWriter filewriter = null;
try {
filewriter = new FileWriter("outUser.txt", true);
BufferedWriter buffWriter = new BufferedWriter(fileWriter);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
buffwriter.write(s1+"\n");
buffWriter.newLine();
buffwriter.flush();
}
catch (IOException e1) {
e1.printStackTrace();
}

Do like this
FileWriter filewriter = null;
try {
filewriter = new FileWriter("c:\\outUser.txt", true);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
filewriter.write("hi"+System.getProperty("line.separator"));
filewriter.write("asd");
filewriter.flush();
}
catch (IOException e1) {
e1.printStackTrace();
}
Use Line Separator Property to print nextline to File .

Related

BufferedWriter and FileWriter writing strange character instead of number to text file Java

I am writing an operation count to a file (denoted as "OpCount") for my program but I keep getting a strange symbol instead of an integer. I tried printing OpCount instead and it outputted the number I was looking for, so its just BufferedWriter doing something strange. Here is my code:
public void writeOpToFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("NumberOperations.txt"));
writer.write(OpCount);
writer.close();
} catch (IOException e) {
System.err.println("File was not found. Please make sure the file exists!");
}
}
public void writeOpToFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("NumberOperations.txt"));
writer.write(new Integer(OpCount).toString());
writer.close();
} catch (IOException e) {
System.err.println("File was not found. Please make sure the file exists!");
}
}

formatting while writing a document

I am reading a txt file into a String buffer and writing the content into a word document using OutputStreamWriter.
The problem is that the formatting is not retained in the document. The spaces and the line breaks are not retained as in the text file. The txt file is formatted properly with spaces, page breaks, and tabs. I want to replicate the txt in word document. Please suggest how can the same formatting be retained. The link to the file is: http://s000.tinyupload.com/index.php?file_id=09876662859146558533.
This is the sample code:
private static String readTextFile() {
BufferedReader br = null;
String content = null;
try {
br = new BufferedReader(new FileReader("ORDER_INVOICE.TXT"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
sb.append(System.lineSeparator());
}
content = sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
private static void createDocument(String docName, String content) {
FileOutputStream fout = null;
try {
fout = new FileOutputStream(docName);
OutputStreamWriter out = new OutputStreamWriter(fout);
out.write(content);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Try to change your readTextFile() like this and try.
BufferedReader br = null;
String content = null;
try {
br = new BufferedReader(new FileReader("ORDER_INVOICE.TXT"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while(line != null) {
content += line + "\n";
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
Actually if your using java 7, you can use try-with-resources in order to decrease the number of lines in your code.
Try to avoid printing \n chars. Use \r\n for Windows - remember that line separators differ across platforms.
A more reliable way is to use PrintWriter, see
How to write new line in Java FileOutputStream
After the discussion in comments:
the source file has unix line breaks
the output file is expected to have Windows line breaks
we shall strip the 0x0c (form feed - i.e. move to next page on the printer) from the source file, as it is non-printable.
public static void main(String[] args) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("f:\\order_invoice.txt")))
.replace("\u000c","");
PrintWriter printWriter=new PrintWriter(new FileWriter("f:\\new_order_invoice.txt"));
for (String line:content.split("\\n")) {
printWriter.println(line);
}
printWriter.close();
}
So:
read the file as it is into a String
get rid of the form feed (0x0c, unicode u000c)
split the string at unix line breaks \n
write it out line by line using PrintWriter which uses the platform default line ending, i.e. windows cr-lf.
Remember that you can actually do this in one line, using a regexp to replace unix line endings to windows line endings in the string representing the whole file, and use Files.write to write out the whole file in one line. However this presented solution is probably a bit better as it always uses platform native line separators.

Write Strings that contain \n with BufferedWriter

If I have a String that contains some words with here and there a \n in between,
is there a way to write them into a .txt file on separate lines? For example:
File myFile = new File("TextFile.txt");
FileWriter fw = null;
try {
fw = new FileWriter(myFile.getAbsoluteFile());
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(myString);
} catch (IOException e) {
e.printStackTrace();
}
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Where myString is something like:
"\nwords\nwords\nwords\n"
With this code I get in the text file words words words instead of
words
words
words
You can either use an editor which understands \n as newline, or use this code:
text = text.replaceAll("\n","\r\n");

Why is my text file not overwriting after each execution?

My program reads in a text file, in.txt. That text file can have an arbitrary amount of lines.
My problem is that when I try to write to the output (out.txt) file, it appends it instead of overwriting.
The output file should have the same number as the input file.
try {
inFile = new Scanner(new File("in.txt"));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
finally {
outFile.flush();
outFile.close();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
The ArrayToString method returns a string to write.
EDIT:
I forgot to add this detail:
After reading the instructions again, I am not supposed to be creating a text file, just checking if it's there.
See the Javadoc for the FileWriter constructor:
public FileWriter(String fileName,
boolean append)
throws IOException
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.
Try setting the append flag to false. Then use the same writer instead of creating a new one each time through the loop (meaning that you should declare the FileWriter above the start of your while loop).
(Btw check out java.util.Arrays.toString, you shouldn't need to write your own code for this.)
The problem is here:
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
Change the PrintWriter line to:
outFile = new PrintWriter((new FileWriter("out.txt", false)));
Now, it looks like you're opening the file on every loop through your input file. If you are wanting to open this file once, and write to it for each line in the input file, move the open and close outside the while loop like this:
try {
inFile = new Scanner(new File("in.txt"));
// here we open the out file, once
outFile = new PrintWriter((new FileWriter("out.txt", false)));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
// this will write a line to the out.txt file containing the intArray as a String
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
finally {
inFile.close();
outFile.flush();
outFile.close();
}
change
outFile = new PrintWriter((new FileWriter("out.txt", true)));
to
outFile = new PrintWriter((new FileWriter("out.txt", false)));
and
outFile.println(ArrayToString(intArray));
to
outFile.print(ArrayToString(intArray));

InputStreamReader is not reading č ž š characters

I'm working on a project, but when I am reading from file it can't read some characters (like č , ž , š, etc.) I dont know what am I am doing wrong.
Here is my code:
try {
reader = new InputStreamReader(getAssets().open("koce_podatki.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(reader);
for(int i=-1;i<position;i++){
try {
temp = "" + br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Your problem is one of encoding. Files only store bytes.
There are many ways to map bytes to characters (those ways are called encoding).
When you read from a text file, you must know and specify which encoding to use.
If you don't specify the encoding in Java, the platform default encoding will be used, which may or may not be what you want.
In your case it is not what you want. To fix this, find out the correct encoding and specify it in the InputStreamReader constructor.
A common encoding to try would be UTF-8. If you told us what you see instead of those characters, we could help you guess the correct encoding.
Try this way:
try {
reader = new InputStreamReader(getAssets().open("koce_podatki.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = new BufferedReader(reader);
while( (s = in.readLine()) != null) {
String UTF8Str = new String(s.getBytes(),"UTF-8"));
temp=""+UTF8Str;
}

Categories