Java中的freopen()
C++中有freopen()函数用来从文件汇中输入测试数组,Java用下面的方式达到这个目的
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 }
转债自:https://www.cnblogs.com/duanguyuan/p/3365843.html
或者下面中方式:
1 public static void main(String[] args) throws Exception { 2 // 输入重定向 3 BufferedInputStream in = new BufferedInputStream(new FileInputStream("std.in")); 4 System.setIn(in); 5 Scanner stdin = new Scanner(System.in); 6 int a = stdin.nextInt(); 7 int b = stdin.nextInt(); 8 // 输出重定向 9 PrintStream out = new PrintStream(new FileOutputStream("estdout.pc2")); 10 System.setOut(out); 11 System.out.print(a + b); 12 out.close(); // 关闭重定向 13 }
转载自:https://blog.csdn.net/fightforyourdream/article/details/17329671