Page List

Search on the blog

2011年1月15日土曜日

Connect a Standard I/O to Files

Today, I'll write about the skill acquired from preparations for Algorithm contests such as HackerCup and CodeJam.

It's about how to connect a standard I/O to designated files. In Java terms, I'd say how to substitute file streams to standard I/O streams.

By using these skills, you can use printf() and cout when writing outputs to files, and you can also use scanf() and cin when reading from files. It's useful, right?
I'll put source codes for both C++ and Java. Before running these codes, make sure that you have made two files, INPUT(containing some integers) and OUTPUT, on your machine.

(Japanese)
今日は、HackerCupやCodeJam対策で学んだ便利なスキルについて。

標準入出力を指定したファイルに結びつける方法です。java風に言うと、標準入出力ストリームにファイルストリームを代入するみたいな感じです。

これを使うと、ファイル出力にprintf(), coutが使えます。ファイル入力にはscanf()、cinが使えます。かなり便利です。
C++、Javaそれぞれでサンプルコードを載せておきます。
INPUTファイルとOUTPUTファイルを作成してから、このソースを実行してください。INPUTファイルにはいくつかの整数を記入してください。

[C++ version]
#define INPUT "C:/input.txt"
#define OUTPUT "C:/output.txt"

int main() {
// connect I/O streams to files
freopen(INPUT, "r", stdin);
freopen(OUTPUT, "w", stdout);

int x;
while (cin >> x) {
cout << x << endl;
}

cerr << "done." << endl;
return 0;
}


[Java version]
public class Main {
static private final String INPUT = "C:/input.txt";
static private final String OUTPUT = "C:/output.txt";

public static void main(String args[]) {
// open I/O files
FileInputStream instream = null;
PrintStream outstream = null;

try {
instream = new FileInputStream(INPUT);
outstream = new PrintStream(new FileOutputStream(OUTPUT));
System.setIn(instream);
System.setOut(outstream);
} catch (Exception e) {
System.err.println("Error Occurred.");
}

Scanner in = new Scanner(System.in);
for (;in.hasNext();) {
int x = in.nextInt();
System.out.println(x);
}

System.err.println("done.");
return;
}

}

3 件のコメント:

  1. Such a useful blog to help me as a freshman who just transferred from C++ to Java! And thanks for the English Version! LoL

    返信削除
  2. Id also wanna to consult you about one point. That in the first two lines of your java version, because you've put the main method in a Main public class, which means we cannot set these two lines in a main method class scope? Can we? Could you explain more with some detials ?

    返信削除