2011-02-10 22 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

++ 'read_string列();'の文字列としないstring.Youのdefination brackatsを削除するか、文字列の前 'class'キーワードを追加する必要を返す関数の宣言です。 – UmmaGumma

+0

[スキャナ](http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html)は、 '' 'のようなものに役立ちます。それぞれの行を読み込み、手動で変換するのは面倒です。 –

+0

C++の例は、 'string read_string();'はあなたが思っていることをしていないので壊れています。また、 '' randomvalue''の代わりに '' random value''を使うとどうなりますか? – 6502

答えて

5

Javaでは、生のバイナリI/OにはInputStreamまたはOutputStreamを使用します。機能を追加するために、これらの上に他のI/Oタイプを作成します。たとえば、BufferedInputStreamを使用して、任意の入力ストリームをバッファにすることができます。バイナリデータを読み書きするときは、生の入力ストリームと出力ストリームの上にDataInputStreamまたはDataOutputStreamを作成すると便利です。そのため、最初にバイト表現に変換せずにプリミティブ型をシリアル化できます。プリミティブに加えてオブジェクトを直列化するときは、ObjectInputStreamObjectOutputStreamが使用されます。テキスト入力の場合、InputStreamReaderは生のバイトストリームをラインベースの文字列入力に変換します(BufferedReaderとFileReaderも使用できます)。PrintStream は同様に、書式付きテキストを生のバイトストリームに簡単に書き込むことができます。 JavaにはI/Oのほうがはるかに多いですが、それらはあなたを始めさせるはずです。

例:Cで

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

} 
+1

+1「>>」の「イディオム」Javaは、[Scanner](http://download.oracle.com/javase/1.5.0/docs/api/java/util/)と思われますが、 Scanner.html)。 –

3

あなたは理解する必要がありますbasic JavaファイルIO。

+0

このリンクは良好です。すべてのコンテンツは1か所にあります。 +1 – Nawaz