1.按行读文件
{
File file = new File("D://temp/test.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
//reader.readLine()容易中文乱码
//new String(tempString.getBytes("utf8"), "gbk")
System.out.println(tempString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.通过字节流读文件
{
File file = new File("D://temp/test.txt");
try {
InputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
int count = 0;
while ((count = inputStream.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, count));
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
}
}
3.解决乱码问题
FileInputStream fileInputStream = new FileInputStream(new File("D://temp/test.txt"));
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "gbk");
BufferedReader reader = new BufferedReader(inputStreamReader);
String tempString = null;
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
}
fileInputStream.close();
inputStreamReader.close();
reader.close();
883

被折叠的 条评论
为什么被折叠?



