Java实现文件内容导入数据库

本文介绍了一种使用Java从指定路径读取文件,并将文件内容解析为Student对象数组的方法。该方法首先打开文件,逐行读取内容,然后按自定义分隔符拆分每行字符串,进而创建并填充Student对象,最终返回对象数组。

public Student[] readFile(String path) {
  String str = null;
String[] array = null;
Student[] stus = new Student[4]; //Student 持久化对象类
int i = 0;
FileReader file = null;
BufferedReader read = null;

try {
file = new FileReader(path); //path 指定文件的路径
read = new BufferedReader(file);

while ((str = read.readLine()) != null ) {
array = str.split("-"); //采用自定义的分割符分割字符串
Student stu = new Student(); //利用临时的Student对象存储一条数据记录
stu.setName(array[0]);
stu.setAge(Integer.parseInt(array[1]));
stu.setSex(array[2]);
stus[i++] = stu;
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
read.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stus
  }

转载于:https://www.cnblogs.com/fuq1109/archive/2013/03/06/2946058.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值