【问题标题】:I'm trying to read a text file and store it in an arraylist of objects我正在尝试读取文本文件并将其存储在对象数组列表中
【发布时间】:2020-02-29 18:29:10
【问题描述】:

我正在尝试读取文本文件并将其存储在对象的数组列表中,但我不断收到错误消息,提示我无法将字符串转换为项目,这是我正在使用的数组列表类型。我尝试了各种解决方案,但不太确定应该如何完成。我是编码新手,很快就会完成这项任务。有什么帮助!

private void loadFile(String FileName)
{
    Scanner in;
    Item line;

    try
    {
        in = new Scanner(new File(FileName));
        while (in.hasNext())
        {
            line = in.nextLine();
            MyStore.add(line);

        }
        in.close();
    }
    catch (IOException e)
    {
        System.out.println("FILE NOT FOUND.");
    }
}

我很抱歉没有添加 Item 类

public class Item
{
private int myId;
private int myInv;

//default constructor
public Item()
{
    myId = 0;
    myInv = 0;
}

//"normal" constructor
public Item(int id, int inv)
{
    myId = id;
    myInv = inv;
}

//copy constructor
public Item(Item OtherItem)
{
    myId = OtherItem.getId();
    myInv = OtherItem.getInv();
}

public int getId()
{
    return myId;
}

public int getInv()
{
    return myInv;
}

public int compareTo(Item Other)
{
    int compare = 0;

    if (myId > Other.getId())
    {
        compare = 1;
    }
    else if (myId < Other.getId())
    {
        compare = -1;
    }
    return compare;
}

public boolean equals(Item Other)
{
    boolean equal = false;

    if (myId == Other.getId())
    {
        equal = true;;
    }
    return equal;
}

public String toString()
{
    String Result;

    Result = String.format("%8d%8d", myId, myInv);

    return Result;
}
}

这是我的arraylist的创建。 私有 ArrayList MyStore = new ArrayList ();

这是我的文本文件的示例。

3679 87

196 60

12490 12

18618 14

2370 65

【问题讨论】:

标签: java sorting arraylist


【解决方案1】:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.rosmery;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Sem-6-INGENIERIAINDU
 */
public class aaa {
    public static void main(String arg[]) throws FileNotFoundException, IOException{
        BufferedReader files=new BufferedReader(new FileReader(new File("")));
        List<String> dto=new ArrayList<>();
        String line;
        while((line= files.readLine())!= null){
            line= files.readLine();
            dto.add(line);
            //Hacer la logica para esos datos
        }
    }
}

【讨论】:

    【解决方案2】:

    in.nextLine() 返回一个String。 因此,您不能将in.nextLine() 分配给Item 的实例。

    您的代码可能需要将其更正为:

        List<String> myStore = new ArrayList<String>();
    
        private void loadFile(String FileName)
        {
            Scanner in;
    
            try
            {
                in = new Scanner(new File(FileName));
                while (in.hasNext())
                {
                    myStore.add(in.nextLine());
                }
                in.close();
            }
            catch (IOException e)
            {
                System.out.println("FILE NOT FOUND.");
            }
        }
    

    如果您想在读取文件后获得Item 的列表,则需要提供将给定信息行转换为Item 实例的逻辑。

    假设您的文件内容采用以下格式。

    id1,inv1
    id2,inv2
    .
    .
    

    然后,您可以使用Item 类型,如下所示。

        List<Item> myStore = new ArrayList<Item>();
    
        private void loadFile(String FileName)
        {
            Scanner in;
    
            String[] line;
    
            try
            {
                in = new Scanner(new File(FileName));
                while (in.hasNext())
                {
                    line = in.nextLine().split(",");
                    myStore.add(new Item(line[0], line[1]));
                }
                in.close();
            }
            catch (IOException e)
            {
                System.out.println("FILE NOT FOUND.");
            }
        }
    

    【讨论】:

      【解决方案3】:

      一种可能的解决方案(假设文件行中的数据用逗号分隔),使用流:

      import java.io.IOException;
      import java.nio.file.Files;
      import java.nio.file.Paths;
      import java.util.List;
      import java.util.stream.Collectors;
      import java.util.stream.Stream;
      
      public class Main {
      
          public static void main(String[] args) throws IOException {
              List<Item> items = loadFile("myfile.txt");
              System.out.println(items);
          }
      
          private static List<Item> loadFile(String fileName) throws IOException {
              try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
                  return stream
                          .map(s -> Stream.of(s.split(",")).mapToInt(Integer::parseInt).toArray())
                          .map(i -> new Item(i[0], i[1]))
                          .collect(Collectors.toList());
              }
          }
      }
      

      或使用 foreach:

      import java.io.IOException;
      import java.nio.file.Files;
      import java.nio.file.Paths;
      import java.util.ArrayList;
      import java.util.List;
      import java.util.stream.Collectors;
      import java.util.stream.Stream;
      
      public class Main {
      
          public static void main(String[] args) throws IOException {
              List<Item> items = new ArrayList<>();
              for (String line : loadFile("myfile.txt")) {
                  String[] data = line.split(",");
      
                  int id = Integer.parseInt(data[0]);
                  int inv = Integer.parseInt(data[1]);
                  items.add(new Item(id, inv));
              }
              System.out.println(items);
          }
      
          private static List<String> loadFile(String fileName) throws IOException {
              try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
                  return stream.collect(Collectors.toList());
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        • 2020-04-05
        • 1970-01-01
        • 2020-02-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多