Java读写TXT文件(读取为数组格式返回)
本文章是读取文件按照行生成数组格式返回如需JSON格式,点击我!!!
实现代码:
读取文件成为数组类型:
/* 读取文件 */
public static String[] readTxtFile(String filePath) {
try {
String encoding = "GBK";
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到文件编码问题
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
List<String> list = new LinkedList<>();
while ((lineTxt = bufferedReader.readLine()) != null) {
// System.out.println(lineTxt);
if (!lineTxt.trim().equals("")) {
list.add(lineTxt);
}
}
System.out.println(list.size());
read.close();
return list.toArray(new String[list.size()]);
} else {
System.out.println("找不到指定文件");
}
} catch (Exception e) {
System.out.println("文件内容读取错误");
e.printStackTrace();
}
return new String[] { "" };
}
代码引用:
readTxtFile(factoryPath);