撸主,「瓜娃」guava 你值得拥有:
import java.io.File;
import java.io.IOException;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
public class App {
public static void main(String[] args) throws IOException {
for (String line : Files.readLines(new File("~/test.txt"), Charsets.UTF_8)) {
System.out.println(line);
}
}
}
ps:看了下源码,是把整个文件读入到 List,大文件会把内存撑爆,可以自己山寨一个:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
for (String line : IO.lineSeq("d:/test.txt")) {
System.out.println(line);
}
}
}
final class IO {
public static Iterable lineSeq(final String path) throws FileNotFoundException {
return new Iterable() {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(
path)));
public Iterator iterator() {
return new Iterator() {
private String content;
public void remove() {
throw new UnsupportedOperationException();
}
public String next() {
return content;
}
public boolean hasNext() {
try {
content = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (content != null) {
return true;
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
};
}
};
}
}