从文本文件中读取和拆分数据

时间:2021-03-11 07:59:18

标签: java

所以我有一个看起来像这样的文本文件...

4234
Bob

6858
Joe

我正在尝试使用 java 读取文件并将数据插入到数组中。我想用那个空行(空格)分隔数据。这是我想出的代码来解决这个问题,但我还没有完全到位。

public class Main {

  public static void main(String[] args) {
    // This name is used when saving the file
    BufferedReader input;
    String inputLine;
    try {
      input = new BufferedReader(new FileReader("test.txt"));
      while ((inputLine = input.readLine()) != null) {
        System.out.println(Arrays.toString(inputLine.split(" ")));
      }
    } catch (IOException e) {
      System.out.println(e.getMessage());
      System.exit(1);
    }
  }
}

我遇到的问题是上面代码的输出看起来像这样

[4234]
[Bob]
[]
[6858]
[Joe]

我想要达到的结果,而我这辈子都想不到如何去实现,是

[4234, Bob]
[6858, Joe]

我觉得很多事情都是相对简单的代码更改;我只是不确定那是什么。

5 个答案:

答案 0 :(得分:0)

您阅读文件的方式不是很方便,在这种情况下.. Scanner 会减轻所有这些工作;然而,如果你坚持,你想使用BufferedReaderFileReader,它会有点冗长、样板甚至是丑陋的代码,像这样:

public class Main {

    public static void main(String[] args) {
        // This name is used when saving the file
        BufferedReader input;
        String inputLine;
        String answer = "";
        try {
            input = new BufferedReader(new FileReader("path\\to\\your\\test.txt"));
            while ((inputLine = input.readLine()) != null) {
                answer = answer + "[" + inputLine + ", ";
                while ((inputLine = input.readLine()) != null && !inputLine.equals("")) {
                    answer += inputLine;
                }
                answer += "]";
                System.out.println(answer);
                answer = "";
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}

此代码,其中 test.txt 包含:

4234
Bob

6858
Joe

4234
John

5352
Martin

将输出:

[4234, Bob]
[6858, Joe]
[4234, John]
[5352, Martin]

答案 1 :(得分:0)

您需要:

  • 二维数组
  • 跟踪您在数组位置中的位置的逻辑
  • 如果您的行是数字/字符串

这听起来像 hw :) 所以我不会解决它,我只会帮助一点。

String[][] myData = define your 2D array;

//您需要创建一个消费者。这就是字符串行,找出将它放入二维数组的位置。

    Consumer<String> processLine = (line) ->  {
        if(StringUtils.isNumeric(line)){
            //Put into array[counter][1]
        }
        else{
            //its a String
            //Put into array[counter][0]
        }
    };

下面的 try/catch,打开一个文件,读取它的行,并按顺序遍历每个行 (forEachOrdered),忽略所有空行,并将其发送给您的 processLine 使用者。

    try (Stream<String> lines = Files.lines(Paths.get("C:/example.txt"), Charset.defaultCharset())) {
        lines.filter(line -> !line.isEmpty()).forEachOrdered(processLine);
    }
    catch (Exception e){
        //Handle Exception
    }

使用 Apache StringUtils http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

如果您不想使用任何外部库。你大概可以做

Integer.parseInt(line) <-- 如果抛出异常,则不是数字

答案 2 :(得分:0)

我不知道您是否需要使用字符串数组,但从长远来看,更好的方法是创建一个类。

class Person {
 public String id;
 public String name;
 public String toString() { return String.format("[%s, %s]", id, name); }
}

(注意:实际上将字段公开是一个坏主意,但这会使代码更短。您可能应该使用 getter 和 setter。

现在您可以在读取文件的同时创建 Person

List<Person> allInFile = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("path\\to\\your\\test.txt"))) {
  String line = reader.readLine();
  while (line != null) {
    line = line.trim();
    // ignore empty lines
    if (line.length() == 0) {
      continue;
    }
    // this is an id; create a person and assign id
    Person person = new Person();
    person.id = line;
    // read consecutive field, which is the name
    person.name = reader.readLine();
    // add the person to the list
    allInFile.add(person);
  }
}
allInFile.forEach(System.out::println);

对此有很多改进,但重点是将两个数据点放在一个类中。

答案 3 :(得分:0)

试试这个代码: 仅当文件包含 number 后跟 name 时才有效,否则对将是不同的格式

对:[数字,字符串]

public static void main(String[] args) {

        BufferedReader input;
        String inputLine;
        List<String> pair = new ArrayList<String>();
        List<String> list = new ArrayList<String>();

        try {
            input = new BufferedReader(new FileReader("Test.txt"));

            while ((inputLine = input.readLine()) != null) {
                if (!inputLine.isEmpty()) {
                    pair.add(inputLine);
                }
                if (pair.size() == 2) {
                    list.add(pair.toString());
                    pair.clear();
                }
            }
            for (String s : list) {
                System.out.println(s);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }

答案 4 :(得分:0)

在查看我的 Stack Overflow 成员发布的答案后,我发现有一种非常简单的方法可以解决这个问题,那就是使用 Scanner 而不是使用 BufferedReader。我不知道为什么我之前没有想到这一点,但事后看来是 2020 年。无论如何,下面的代码是我用来解决问题的。

public static void main(String[] args) {
  ArrayList<String> test = new ArrayList<>();
  File file = new File("test.txt");
  try {
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
      test.add(sc.next()); // The id
      test.add(sc.next()); // The name
    }
    sc.close();
    System.out.println(test.toString());
   } catch (FileNotFoundException e) {
    e.printStackTrace();
  }
}

所做的就是让每一行都有不同的数据,并跳过空白。从那里它将它添加到 ArrayList 以供以后处理。记住 K.I.S.S(Keep It Simple Stupid)不需要把任何事情复杂化。