【问题标题】:Reading file to ArrayList读取文件到 ArrayList
【发布时间】:2014-05-17 11:21:41
【问题描述】:

我正在尝试将 .dat 文件写入 ArrayList。该文件包含格式如下的行:#name#,#number#。

Scanner s = new Scanner(new File("file.dat"));
while(s.hasNext()){
    String string = s.next();
    names.add(string.split(",")[0];
    numbers.add(Integer.parseInt(string.split(",")[1];
}

如果我检查它是否与打印一起运行,我得到的只是第一行。

【问题讨论】:

  • 如何检查它是否运行?您是否在 IDE 中运行它并在断点处停止?
  • 我只是为所有内容添加了打印命令,比如我打印字符串,然后是拆分的字符串......
  • 你能告诉你确切的数据格式吗
  • 如果格式真的是 "#name#,#number# 你会得到一个异常,因为你试图将 #number# 解析为一个 int。如果你的格式是 name,442 它按预期对我有用对于整个文件
  • 我很好奇,有人有使用 Java 8 Sream API 的答案吗?

标签: java text input


【解决方案1】:

使用标准 Java 库(完整代码示例):

BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {   
    in = new BufferedReader(new FileReader("myfile.txt"));
    String str;
    while ((str = in.readLine()) != null) {
        myList.add(str);
        //Or split your read string here as you wish.
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (in != null) {
        in.close();
    }
}

与其他常用库:

commons-io 的单线:

List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");

guava:

List<String> lines = 
     Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));

然后您可以遍历读取的行并将每个字符串拆分为所需的 ArrayList。

【讨论】:

  • 从 Java 7 开始,标准库中有一个很好的方法来读取文件:List&lt;String&gt; lines = Files.readAllLines(Paths.get("abc.txt"), StandardCharsets.UTF_8);
【解决方案2】:

不要使用Scanner,而是使用BufferedReaderBufferedReader 提供了一种一次读取一行的方法。使用它,您可以通过拆分 (line.split(",")) 来单独处理每一行,剥离尾随哈希,然后将它们推送到您的 ArrayLists 中。

【讨论】:

    【解决方案3】:

    这就是我读取文件并将其转换为数组列表的方式

        public List<String> readFile(File file){
        try{
            List<String> out = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line;
            while((line = reader.readLine()) != null){
                if(line != null){
                    out.add(line);
                }
            }
            reader.close();
            return out; 
        }
        catch(IOException e){
    
        }
        return null;
    }
    

    希望对你有帮助。

    【讨论】:

    • 如果我尝试你的方法,我会一直遇到同样的问题。如果我打印出姓名和号码,我只会得到第一个,但是当我删除与列表有关的行时,一切都会被打印出来
    【解决方案4】:

    这可能是一个漫长的过程,但有效:

    文本文件:

    susheel,1134234
    testing,1342134
    testing2,123455
    

    主类:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Equal {    
        public static void main(String[] args) {        
            List<Pojo> data= new ArrayList<Pojo>();
            String currentLine;
            try {
                BufferedReader br = new BufferedReader(new FileReader("E:\\test.dat"));
                while ((currentLine = br.readLine()) != null) {
                    String[] arr = currentLine.split(",");
                    Pojo pojo = new Pojo();
                    pojo.setName(arr[0]);
                    pojo.setNumber(Long.parseLong(arr[1]));
                    data.add(pojo);
                }
                for(Pojo i : data){
                    System.out.print(i.getName()+" "+i.getNumber()+"\n");
                }
            } catch (Exception e) {
                System.out.print(e.getMessage());
            }
    
        }
    }
    

    POJO 类:

    public class Pojo {    
        String name;
        long number;
    
        public String getName() {
            return name;
        }    
        public void setName(String name) {
            this.name = name;
        }    
        public long getNumber() {
            return number;
        }    
        public void setNumber(long number) {
            this.number = number;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      相关资源
      最近更新 更多