2011-02-10 51 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。