Output problem (newbie Q)
Hello. I am learning java and tried to make a simple program, which reads the int number and writes it into a file. The problem is - the txt file remains empty. Take a look at the code:
Code :
import java.io.*;
import java.util.*;
class Job {
int x;
public int inputTxt() {
try {
x = System.in.read();
} catch (Exception e) {
System.out.println("input error");
}
return x;
}
public void outputF() {
try {
OutputStream f = new FileOutputStream("test.txt");
f.write(x);
} catch (Exception e) {
System.out.println("output error");
}
}
public void closeF() {
try {
OutputStream f = new FileOutputStream("test.txt");
f.close();
} catch (Exception e) {
System.out.println("close error");
}
}
}
class Test {
public static void main(String args [ ]) {
Job j = new Job();
j.inputTxt();
j.outputF();
j.closeF();
}
}
Re: Output problem (newbie)
The f object in the close method is NOT the same as the f object in the write method.
Close the output file after writing to it or have a reference to the object that was written to when closing it.
Quote:
txt file remains empty
What is the size of the output file? Is it 0? What does the write() method output to the file?
Look at the file with a hex editor.
Re: Output problem (newbie)
Quote:
Originally Posted by
Norm
The f object in the close method is NOT the same as the f object in the write method.
Close the output file after writing to it or have a reference to the object that was written to when closing it.
What is the size of the output file? Is it 0? What does the write() method output to the file?
Look at the file with a hex editor.
Ok, I go it, thanks a lot! ;)
Yes, the txt file had 0 b size.
Re: Output problem (newbie)
I got output (1 byte) when I ran your code (except I moved the close to the outputF() method).
Re: Output problem (newbie)
Quote:
Originally Posted by
Norm
I got output (1 byte) when I ran your code (except I moved the close to the outputF() method).
I did the same and it solved the problem.
Re: Output problem (newbie)
I guess what happened is you created a file and wrote to it. Then in the closeF() method you created a new file with the same name and wrote nothing to it destroying the first version.