JAVA支持字符编码读取文件

时间:2023-03-09 19:12:21
JAVA支持字符编码读取文件

文件操作,在java中很常用,对于存在特定编码的文件,则需要根据字符编码进行读取,要不容易出现乱码

         /**
* 读取文件
* @param filePath 文件路径
*/
public static void readFile(String filePath) {
FileInputStream fis = null;
BufferedReader br = null; String line = null;
try {
fis = new FileInputStream(filePath);
br = new BufferedReader(new InputStreamReader(fis));
while (null != (line = br.readLine())) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 释放资源
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

使用字符编码读取文件,防止乱码

         /**
* 读取文件,使用字符编码读取文件,防止乱码
* 字符编码参数如果为空或者null,则使用默认读取文件
*
* @param filePath 文件路径
* @param encodingStr 字符编码
*/
public static void readFile(String filePath, String encodingStr) {
if (null == encodingStr || encodingStr.trim().length() <= 0) {
readFile(filePath);
} else {
FileInputStream fis = null;
BufferedReader br = null; String line = null;
try {
fis = new FileInputStream(filePath);
// 使用字符编码读取文件,防止乱码
br = new BufferedReader(new InputStreamReader(fis, encodingStr));
while (null != (line = br.readLine())) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 释放资源
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} }