在作ACM題目的時候,爲節省輸入測試數據的時間,咱們一般將數據複製到一個文本文檔裏,而後從文檔裏讀出,避免在控制檯一個數據一個數據的輸入。html
以前一直用的C/C++,freopen用起來很方便,以下:java
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),傳送門,點開絕對有驚喜!也是一個日本程序員的我的博客。厲害!google