通过这种方式,可以在刷算法的时候用文件操作来代替手动输入数据,提高效率。
1.static void setErr(PrintStream err):重定向”标准”错误输出流.
2.static void setIn(InputStream in):重定向”标准”输入流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintStream; import java.util.Scanner; public class FileTest { public static void main(String[] args) throws FileNotFoundException { // 保存原始控制台输入输出流 InputStream in = System.in; PrintStream out = System.out; // 重定向输入输出到文件中 System.setIn(new FileInputStream("in.txt")); System.setOut(new PrintStream("out.txt")); // 测试文件输入输出 Scanner sc = new Scanner(System.in); while (sc.hasNextInt()) { int a = sc.nextInt(); int b = sc.nextInt(); System.out.println(a + b); } // 输入输出流重定向会控制台 System.setIn(in); System.setOut(out); // 测试输入输出 Scanner ssc = new Scanner(System.in); int test = ssc.nextInt(); System.out.println("输入输出流重回控制台 " + test); } } |