Java:从文本文件中读取内容来创建对象?

时间:2015-05-19 15:08:49

标签: java file

我试图从类似于:

的文本文件中读取
exampleName1 exampleAddress1
exampleName2 exampleAddress2

如何通过阅读文本文件中的每一行来创建具有名称和地址的对象?

E.g: Record record1= new Record(name, address);

我试图使用Scanner,但我不确定如何准确。

Scanner myscanner= new Scanner (new FileInputStream(myfile.txt);

while (myscanner.hasnext()){

//read from file?

}

//create object here...

2 个答案:

答案 0 :(得分:2)

我会做这样的事情:

List<Record> records = new ArrayList<>();
Scanner myscanner= new Scanner (new FileInputStream("myfile.txt"));
while (myscanner.hasnext()){
  String line = myscanner.readline();
  int index = line.indexOf(' ');
  String name = line.substring(0, index-1);//TODO check...
  String address = line.substring(index);
  records.add(new Record(name, address);
}

未经测试的代码,但应该工作(不知何故)。如果您遇到问题,请更具体地说明问题。

编辑:当然扫描仪没有readline()。顺便说一句。为什么要使用扫描仪?使用BufferedReader和正确的InputStreamReader,你可以做到。

EDIT2: 正确的意思是,你传递文件的Charset如下:new InputStreamReader("filename", StandardCharsets.UTF_8)(或者文件的Charset是......)

答案 1 :(得分:0)

请多搜索一下,找出这么简单的答案......

Cave of Programming exemple

我会尝试这样的事情:

try {
    String line;
    String[] splitedLine;
    String name;
    String address;

    BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
    while((line=br.readLine()) != null) {
        splitedLine = line.split(' ');
        name = splitedLine[0];
        address = splitedLine[1];
        new Record(name,address);
        //You could also do new Record(splitedLine[0],splitedLine[1]);
    }
} catch (IOException e) {
    e.printStackTrace();
}