Skip to content

Instantly share code, notes, and snippets.

@limboinf
Created September 28, 2017 15:05
Show Gist options
  • Save limboinf/ceca9958ccb1fa7cb0b18c7666e8cad0 to your computer and use it in GitHub Desktop.
Save limboinf/ceca9958ccb1fa7cb0b18c7666e8cad0 to your computer and use it in GitHub Desktop.
[Java File read] #java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Main {
/**
* 步骤:
* 1. File 创建文件句柄
* 2. FileInputStream(fp): fp -> buffer, 进来内存当中
* 3. InputStreamReader: 解读buffer内存数据,如通过什么编码
* 4. BufferedReader: 调用字节码读取的方法BufferedReader()准备数据读出来
* @param filePath
*/
public static void readFile(String filePath) {
try {
String encoding = "utf-8";
File fp = new File(filePath);
if (fp.isFile() && fp.exists()) {
InputStreamReader reader = new InputStreamReader(new FileInputStream(fp), encoding);
BufferedReader buffReader = new BufferedReader(reader);
String line;
while ((line = buffReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} else {
System.out.println("找不到该文件");
}
} catch (Exception e) {
System.out.println("文件读取失败");
e.printStackTrace();
}
}
public static void main(String[] args)
{
readFile("/Users/fzq/project/my.txt");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment