这是文件里的内容。
1,2,3,4,5,6,7,8
8,7,6,5,4,3,2,1
一,二,三,四,五, , , ,
五,四,三,二,一, , , ,
代码开始了。
public static String totalfilesrcpath = "D:/file/";
public static String enterfilesrcpath = "D:/file/file1";
public static ArrayList<FileData> filereq = new ArrayList<FileData>();
/**
* 以行为单位读取文件
*/
public static void readFileByLines() {
File[] ftpFiles = new File(totalfilesrcpath).listFiles();// 此目录下所有文件
if (ftpFiles != null && ftpFiles.length > 0) {
for (File ftpFile : ftpFiles) {
String yfilename = ftpFile.getName();
if (yfilename.equals("file")) {
BufferedReader reader = null;
try {
System.out.println("\n以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(ftpFile));
String tempString = null;// 把每一行读取到的文件赋值给临时变量
FileData data = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
//以逗号分隔、去逗号
String[] cs = tempString.split(",");
data = new FileData();
//把元素一一赋值给对象
data.setTest1(cs[0]);
data.setTest2(cs[1]);
data.setTest3(cs[2]);
data.setTest4(cs[3]);
data.setTest5(cs[4]);
data.setTest6(cs[5]);
data.setTest7(cs[6]);
data.setTest8(cs[7]);
filereq.add(data);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
}
//测试
public class TestReadFile {
public static void main(String[] args) {
// 按行读取文件
ReadFromFile.readFileByLines();
}
}
