Reputation: 1100
I wrote this code to convert binary data to ascii , now I want to write the console result into a textfile output.txt . it runs but the problem is it prints the first line into console and start writing the output to textfile from the second line , on other words it skip the fisr line !
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String input = br.readLine();
String output = "";
for(int i = 0; i <= input.length() - 8; i+=8)
{
int k = Integer.parseInt(input.substring(i, i+8), 2);
output += (char) k;
}
System.out.println("string: " + output);
orgStream = System.out;
fileStream = new PrintStream(new FileOutputStream("d:/output.txt",true));
// Redirecting console output to file
System.setOut(fileStream);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
these line are responsible for writing the result into output.txt:
System.out.println("string: " + output);
orgStream = System.out;
fileStream = new PrintStream(new FileOutputStream("d:/output.txt",true));
// Redirecting console output to file
System.setOut(fileStream);
how can I save output in eclipse to be able to use that again ? now I save in D drive
Upvotes: 0
Views: 2716
Reputation: 3913
This line
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
simply redirects whatever you write to System.out to a FileOutputStream. Since you are not writing anything to System.out, nothing is written to output.txt.
Instead of redirecting System.out, you could simply write your output to the PrintStream you created. So first create the PrintStream outside the while loop and then inside the loop write each character you create directly to the PrintStream. No need to redirect System.out or (inefficiently) concatenate the characters into a String.
Also, when you are done writing, you should close() the streams you created. This is just a good practice to learn before you start writing bigger programs where leaving streams open can cause bugs.
Upvotes: 1
Reputation: 36229
I guess you need an
out.flush ();
in the end. On a second look, I see, you never write anything to out. Do you only want to write error messages as Anantha suggests?
You forgot the:
System.out.println (output);
Upvotes: 0
Reputation: 10098
the code
System.err.println("Error: " + e.getMessage());
will write to the error stream and not the out stream..
System.setOut(out);
here you are setting the out stream, the err stream still defaults to the console.
Upvotes: 0