【问题标题】:Java: Reading in multiple different string variables from a single line of a txt fileJava:从 txt 文件的单行读取多个不同的字符串变量
【发布时间】:2018-06-27 09:01:09
【问题描述】:

我有一个格式如下的文本文件:

[Employee ID], [Full Name], [Rate of Pay]

一对示例行如下所示:

32483, William Ellis, 25.50

58411, Jonathan Ian Morris, 15.00 

我正在尝试读取文本文件中的所有员工,并为每个员工创建对象,将姓名、ID 和工资存储在哈希图中。我将 EmpID 作为字符串,员工姓名作为字符串,工资作为双倍。我的问题是它将 EmpID 读取为包含“,”的字符串,然后它将名字作为名称变量读取,然后尝试将中间名或姓氏作为双精度名称,并附加“,”。因此,例如它会如下所示:

empID: "32483,"

全名:“威廉”

工资:Ellis(产生错误)

while(inputFile.hasNext()) {
        empID = inputFile.next();
        fullName = inputFile.next();
        wage = inputFile.nextDouble();
        empmap.put(empID, new Employee(empID, fullName, wage));
    }

我想我可以试试名字和姓氏,但有些人有中间名,或者只是一个名字。我还考虑了将每个字符逐个字符并将它们连接起来的可能性,同时使用“,”作为一种空字符,让程序知道它之前的所有内容都是一个字符串并且新字符串即将开始但在我尝试这样的事情之前,我认为必须有一个更简单的解决方案。

【问题讨论】:

  • Scanner.next() 默认使用空格作为分隔符。所以,改变分隔符。或者阅读下一行,并使用 String.split() 拆分逗号字符。或者使用 CSV 解析器。

标签: java string file io


【解决方案1】:

您可以使用拆分来处理此问题。在您的示例中:

String [] data = inputFile.split(","); 
empId = Integer.parseInt(data[0]);
fullname = data [1]; 
(...)

祝你好运

【讨论】:

    【解决方案2】:

    试试这个代码:

     public static void main(String[] args) throws FileNotFoundException {
            Scanner input = new Scanner(new File("employee.txt"));
            input.useDelimiter(",|\n");
    
            Employee[] emps = new Employee[0];
            while(input.hasNext()) {
                int id = input.nextInt();
                String fullname = input.next();
                double payrate = Double.valueOf(input.next().substring(1));
    
                Employee newEmp = new Employee(fullname, payrate, id);
                emps = addEmployee(emps, newEmp);
            }
    
            for (Employee e : emps) {
                System.out.println(e);
            }
        }
    
        private static Employee[] addEmployee(Employee[] emps, Employee empToAdd) {
            Employee[] newEmps = new Product[products.length + 1];
            System.arraycopy(products, 0, newProducts, 0, products.length);
            newEmps[newEmps.length - 1] = empToAdd;
    
            return newEmps;
        }
    
        public static class Employee {
            protected int id;
            protected String fullname;
            protected double payrate;
    
            private static NumberFormat formatter = new DecimalFormat("#0.00");
    
            public Product(String n, double p, int i) {
                id = i;
                fullname= n;
                payrate = p;
    
            }
    

    【讨论】:

      【解决方案3】:

      假设每一行都有特定的常量格式,您可以执行以下操作:

      逐行读取文件。对于每一行:

      1. 在每一行中拆分字符串。 (用逗号,
      2. 解析分割字符串的各个部分
      3. 放入某个集合中

      读取文件非常简单。 This answer 可以作为参考。

      BufferedReader br = new BufferedReader(new FileReader("file.txt"));
      try {
          String line = br.readLine();
      
          while (line != null) {
      
              line = br.readLine();
              String[] splitStr=line.split(", ");
              if(splitStr.length==3){
                  int empID=Integer.parseInt(splitStr[0]);
                  String fullName=splitStr[1];
                  double wage=Double.parseDouble(splitStr[2]);
              }
          }
      
      } finally {
          br.close();
      }
      

      【讨论】:

        【解决方案4】:

        我的偏好是使用Files.lines 获取包含文件每一行的流,然后根据分隔符拆分每一行:

        public class Main
        {
            public static void main(final String... args) throws Exception
            {
                Files.lines(Paths.get("path/to/my/file"))
                     .forEach(Main::processLine);
            }
        
            private static void processLine(final String line)
            {
                final String[] tokens = line.split(",");
                final String id = tokens[0].trim();
                final String name = tokens[1].trim();
                final String rateOfPay = tokens[2].trim();
        
                //...
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2016-02-09
          • 2015-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-01
          • 2022-09-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多