一.写字节数组
<span style="font-size:14px;">public static void fileWrite(String fileName, String contents) {
final File newFile = new File(fileName);
try {
Files.write(contents.getBytes(), newFile);
} catch (IOException e) {
e.printStackTrace();
}
}</span>
二.读文件(一次性读完)
<span style="font-size:14px;">public static void fileRead(String fileName) {
File testFile = new File(fileName);
try {
List<String> lines = Files.readLines(testFile, Charsets.UTF_8);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}</span>
<span style="font-size:14px;">static class CounterLine implements LineProcessor<Integer> {
private int rowNum = 0;
@Override
public boolean processLine(String line) throws IOException {
rowNum ++;
return true;
}
@Override
public Integer getResult() {
return rowNum;
}
}
/**
* 逐行读取
* @param fileName
*/
public static void fileReadByLine(String fileName) {
File testFile = new File(fileName);
CounterLine counter = new CounterLine();
try {
Files.readLines(testFile, Charsets.UTF_8, counter);
System.out.println(counter.getResult());
} catch (IOException e) {
e.printStackTrace();
}
}</span>