版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Fei20140908/article/details/82561781
常用(比较简单)的输入输出一般是这样:
Scanner in = new Scanner(System.in);
in.hasNext();
in.nextInt();
...
但是有时候比如 ACM,会希望像c++中那样使用
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
cin >> a; // 从文件读
cout << a; // 输出到文件
输入输出重定向
进行输入输出重定向,而不是用fostream,这样可以在提交代码的时候直接注释掉重定向的代码就可以恢复标准流的输入输出。
那么在java 里是如何做的呢?其实也差不多
System.setIn(new FileInputStream("in.txt"));
System.setOut(new PrintStream(new FileOutputStream("out.txt")));
Scanner sc = new Scanner(System.in); // 从文件扫描
System.out.println(); // 输出到文件
...
读写加速
使用Scanner 的速度比较慢,在做acm题时,我发现用scanner速度比其他人慢了3~4倍!所以琢磨了下别人的代码,发现可以进行读写加速
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
in.nextToken() != StreamTokenizer.TT_EOF ; // == sc.hasNext();
int a = (int)in.nval; // == sc.nextInt();
in.nextToken(); // 每读一个要执行这个,不然读的是同一个
out.println("hello world");
out.flush(); // 要想显示就得flush,不然留在缓冲区
上面的代码中的System.in,System.out 可以重定向,然后你懂得。
最后举个完整的例子:
import java.io.*;
public class MinMax {
public static void main(String [] args) throws IOException {
System.setIn(new FileInputStream("src\\in.txt"));
System.setOut(new PrintStream(new FileOutputStream("src\\out.txt")) );
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
while(in.nextToken() != StreamTokenizer.TT_EOF){
int n = (int)in.nval;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
in.nextToken();
for(int i=0; i<n; i++){
int tmp = (int)in.nval;
in.nextToken();
if(min > tmp) {
min = tmp;
}
if (max < tmp) {
max = tmp;
}
}
out.println(max+" "+min);
out.flush();
}
}
}