zoukankan      html  css  js  c++  java
  • 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),传送门,点开绝对有惊喜!也是一个日本程序员的个人博客。厉害!

  • 相关阅读:
    Binary Tree Maximum Path Sum
    4Sum
    Candy
    Simplify Path
    Max Points on a Line
    ZigZag Conversion
    Two Sum
    Effective_STL 学习笔记(十二) 对STL线程安全性的期待现实一些
    Effective_STL 学习笔记(十一) 理解自定义分配器的正确用法
    Effective_STL 学习笔记(九) 在删除选项中仔细选择
  • 原文地址:https://www.cnblogs.com/duanguyuan/p/3365843.html
Copyright © 2011-2022 走看看