java中的freopen

在做ACM题目的时候,为节省输入测试数据的时间,我们通常将数据复制到一个文本文档里,然后从文档里读出,避免在控制台一个数据一个数据的输入。

之前一直用的C/C++,freopen用起来很方便,如下:

 1 #define INPUT "C:/input.txt"
 2 #define OUTPUT "C:/output.txt"
 3 
 4 int main() {
 5   // connect I/O streams to files
 6   freopen(INPUT, "r", stdin);
 7   freopen(OUTPUT, "w", stdout);
 8 
 9   int x;
10   while (cin >> x) {
11       cout << x << endl;
12   }
13 
14   cerr << "done." << endl;
15   return 0;
16 }

 

最近转到java,一时半会儿诸多不习惯,其中就有这个问题,java里怎么写“freopen”?如下:

 1 public class Main {
 2   static private final String INPUT = "C:/input.txt";
 3   static private final String OUTPUT = "C:/output.txt";
 4 
 5   public static void main(String args[]) {
 6       // open I/O files
 7       FileInputStream instream = null;
 8       PrintStream outstream = null;
 9    
10       try {
11           instream = new FileInputStream(INPUT);
12           outstream = new PrintStream(new FileOutputStream(OUTPUT));
13           System.setIn(instream);
14           System.setOut(outstream);
15       } catch (Exception e) {
16           System.err.println("Error Occurred.");
17       }
18    
19       Scanner in = new Scanner(System.in);
20       for (;in.hasNext();) {
21           int x = in.nextInt();
22           System.out.println(x);
23       }
24    
25       System.err.println("done.");
26       return;
27   }
28 
29 }

google了很多地方才找到这个模板,貌似来自一个日本的站点:http://techtipshoge.blogspot.com/2011/01/connect-standard-io-to-files.html

更厉害的一个站点,讲不同语言中的标准输入输出重定向(freopen),传送门,点开绝对有惊喜!也是一个日本程序员的个人博客。厉害!

 

posted @ 2013-10-12 20:03  duanguyuan  阅读(1380)  评论(0编辑  收藏  举报