BufferedRead + FileReader
开了一个BufferedReader
,只能按字节读,所以自己写了个getint()
。
看很多人用了readLine() + str.split(" ") + Integer.parseInt()
感觉不如手写方便。
读文件还要throw exception。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
static int len;
static int[] a = new int[10000];
private static BufferedReader br;
public static int getint() throws IOException {
int x = br.read();
while (x < '0' || x > '9') x = br.read();
int ret = 0;
while (x >= '0' && x <= '9') {
ret = ret * 10 + (x - 48);
x = br.read();
}
return ret;
}
public static void init() throws IOException {
br = new BufferedReader(new FileReader("resource/in.txt"));
len = getint();
for (int i = 1; i <= len; i++) {
a[i] = getint();
}
}
public static void print() {
for (int i = 1; i <= len; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) throws IOException {
init();
print();
}
}
FileInputStream & FileOutputStream
这个是流输入输出,本来想用的,直到我发现 FileReader
和 FileWriter
就是包装过后的FileInputStream
和 FileOutputStream
。所以被我抛弃了。
FileReader & FileWriter
FileWrtier()
终于不用按byte输出了,还是这一对input和output用起来舒服。读入其实直接读byte就好了,不用套个buffer。
文件输出需要close,不然就掉了。
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
static int len;
static int[] a = new int[10000];
private static FileReader fin;
private static FileWriter fout;
public static int getint() throws IOException {
int x = fin.read();
while (x < '0' || x > '9') x = fin.read();
int ret = 0;
while (x >= '0' && x <= '9') {
ret = ret * 10 + (x - 48);
x = fin.read();
}
return ret;
}
public static void init() throws IOException {
fin = new FileReader("resource/in.txt");
len = getint();
for (int i = 1; i <= len; i++) {
a[i] = getint();
}
}
public static void print() throws IOException {
fout = new FileWriter("resource/out.txt");
for (int i = 1; i <= len; i++) {
fout.write(a[i] + " ");
}
fout.close();
}
public static void main(String[] args) throws IOException {
init();
print();
}
}