问题描述
请注意,这不是一个更好的讨论。
Note that this is NOT a "better-than" discussion.
我是一个C ++程序员,它让我感到难以置信的愚蠢不知道如何做非常多的Java文件IO。
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 integers and Strings of variable length.
在C ++中,我可以使用:
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;
非常感谢!
推荐答案
在Java中,您使用或
用于原始二进制I / O。除了这些之外,还可以组合其他I / O类型,以添加功能。例如,您可以使用使任意输入流变得缓冲。在读取或写入二进制数据时,通常可以方便地创建或顶部的原始输入和输出流,以便您可以序列化任何基本类型,而无需先将其转换为其字节表示。当序列化除了图元之外的对象时,可以使用和。对于文本I / O,将原始字节流转换为基于行的字符串输入(您也可以使用BufferedReader和FileReader),而
同样使格式化的文本写入原始字节流变得容易。
In Java, you use a InputStream or OutputStreamfor 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 PrintStreamsimilarly 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.
例如:
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 Line IO和C ++ IO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!