2011-02-10 113 views
1

请注意,这不是一个“好于”的讨论。Java线IO与C++ IO?

我是一名C++程序员,它让我感到非常愚蠢,不知道如何去做非常多的Java文件IO。

我需要在一个文件中存储一些不同的数据类型,以便稍后回读。这些包括整数和可变长度的字符串。

在C++中,我可以只使用:

//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; 

非常感谢!

+1

在C++`串read_string();`是函数声明,它返回字符串和不string.You的认定中必须删除brackats或字符串之前添加`class`关键字。 – UmmaGumma 2011-02-10 07:13:17

+0

[Scanner](http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html)可以帮助使用类似于“>>”的东西。当阅读每一行并手动转换时,这会有点痛苦;-) – 2011-02-10 07:22:39

+0

你的C++示例已经破坏,因为`string read_string();`没有做你明显想到的。你也知道如果你使用``random value'`而不是``randomvalue'``会发生什么? – 6502 2011-02-10 07:23:32

回答

5

在Java中,对原始二进制I/O使用InputStreamOutputStream 。为了增加功能,您可以在其他I/O类型之上编写这些类型。例如,您可以使用BufferedInputStream来使任意输入流成为缓冲区。在读取或写入二进制数据时,在原始输入和输出流之上创建DataInputStreamDataOutputStream通常很方便,这样您就可以序列化任何基本类型,而无需先将其转换为它们的字节表示形式。除了基元以外,还要序列化对象,其中一个使用ObjectInputStreamObjectOutputStream。对于文本I/O,InputStreamReader将原始字节流转换为基于行的字符串输入(您也可以使用BufferedReader和FileReader),而PrintStream 类似地使得格式化文本容易写入原始字节流。 Java中的I/O比这还多,但这些应该让你开始。

实施例:

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) { 
    // ... 
    } 
    // ... 

} 
3

您需要了解basic java文件IO。