读取txt文件java
package ada;
import java.io.*;
import java.util.ArrayList;
public class duqu {
public static ArrayList<String> getTxt(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 reader=new BufferedReader(read);
ArrayList<String> readList = new ArrayList<String>();
String temp = null;
while((temp=reader.readLine())!=null &&!"".equals(temp)){
readList.add(temp);
}
read.close();
return readList;
}else{
System.out.println("找不到指定的文件");
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
return null;
}
}
运行
package ada;
import java.util.ArrayList;
import ada.duqu;
public class from {
public static void main(String[] args) {
String filePath = "C:\\Users\\Administrator\\Desktop\\7.txt";
// "res/";
ArrayList<String> retList = duqu.getTxt(filePath);
for(int i=0;i<retList.size();i++) {
System.out.println(retList.get(i));
}
}
}