开发者

Java Line IO vs C++ IO?

Note that this is NOT a "better-than" discussion.

I'm a C++ programmer, and it makes me feel incredibly dumb not to know how to do very much Java file IO.

I need to store a number of different data types in a file to be read back later. These include i开发者_Go百科ntegers and Strings of variable length.

In C++, I could just use:

//wont actually know the value of this
string mystr("randomvalue");
//the answer to the Ultimate Question of Life, the Universe, and Everything
int some_integer = 42;

//output stream
ofstream myout("foo.txt");
//write the values
myout << mystr << endl;
myout << some_integer << endl;

//read back
string read_string;
int    read_integer;

//input stream
ifstream myin("foo.txt");
//read back values
//how to do accomplish something like this in Java?
myin >> read_string;
myin >> read_integer;

Thanks very much!


In Java, you use a InputStream or OutputStream for raw binary I/O. You compose other I/O types on top of these in order to add functionality. For example, you might use a BufferedInputStream to make an arbitrary input stream become buffered. When reading or writing binary data, it is often convenient to create a DataInputStream or DataOutputStream on top of the raw input and output streams, so that you can serialize any primitive type without first having to convert them to their byte representations. When serializing objects in addition to primitives, one uses a ObjectInputStream and ObjectOutputStream. For text I/O, InputStreamReader converts a raw byte stream into line-based string input (you can also use BufferedReader and FileReader), while PrintStream similarly makes writing formatted text to a raw byte stream easy. There is a lot more to I/O in Java than that, but those should get you started.

Example:

void writeExample() throws IOException {
   File f = new File("foo.txt");
   PrintStream out = new PrintStream(
                         new BufferedOutputStream(
                             new FileOutputStream(f)));
   out.println("randomvalue");
   out.println(42);
   out.close();
}

void readExample() throws IOException {
   File f = new File("foo.txt");
   BufferedReader reader = new BufferedReader(new FileReader(f));
   String firstline = reader.readLine();
   String secondline = reader.readLine();
   int answer;
   try {
     answer = Integer.parseInt(secondline);
   } catch(NumberFormatException not_really_an_int) {
     // ...
   }
   // ...

}


You need to understand basic java File IO.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜