Java Line 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 <> read_string; myin >> read_integer; 

非常感谢!

在Java中,您将InputStream或OutputStream用于原始二进制I / O. 您可以在其上添加其他I / O类型以添加​​function。 例如,您可以使用BufferedInputStream使任意输入流变为缓冲。 在读取或写入二进制数据时,通常可以在原始输入和输出流之上创建DataInputStream或DataOutputStream ,这样您就可以序列化任何基本类型,而无需先将它们转换为字节表示forms。 除了基元之外还序列化对象时,可以使用ObjectInputStream和ObjectOutputStream 。 对于文本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) { // ... } // ... } 

您需要了解基本的 Java File IO。