gpt4 book ai didi

java - 读取文本文件,然后将其拆分为不同的数组

转载 作者:行者123 更新时间:2023-12-01 16:58:35 24 4
gpt4 key购买 nike

所以我尝试使用 BufferedReader 将文本文件拆分为 2 个不同的数组,我已经编写了一些代码,但我不确定从哪里开始。

我知道如何填充数组,但我似乎无法获取特定的行。

因此,NEW_OFFICE 的一个数组仅包含数字,MAIN_ADDRESS 的一个数组仅包含其下方的数字。

BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("myDelivery.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String words = read.split("NEW_OFFICE")[0];
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception ignored) { }
}

这是文本文件:

NEW_OFFICE
-92.48392883 52.96531732
-2.483984994 92.48392883
MAIN_ADDRESS
-1.207614869 52.98908196

最佳答案

NEW_OFFICE always is the first line, and always has two lines below it, the same goes for MAIN_ADDRESS it always has one line below it. NEW_OFFICE & MAIN_ADDRESS can't appear more than once.

根据您上面提到的评论,解决方案如下:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class Main {
public static void main(String[] args) throws IOException {
String[][] office = new String[2][2];
String[][] main = new String[1][2];
try (BufferedReader in = new BufferedReader(new FileReader("myDelivery.txt"))) {
String read;
while ((read = in.readLine()) != null) {
if (read.equalsIgnoreCase("NEW_OFFICE")) {
// Read next two lines
for (int i = 0; i < 2; i++) {
if ((read = in.readLine()) != null) {
office[i] = read.split("\\s+");
}
}
} else if (read.equalsIgnoreCase("MAIN_ADDRESS")) {
// Read next line
if ((read = in.readLine()) != null) {
main[0] = read.split("\\s+");
}
}
}
}
// Display office[][]
System.out.println("Displaying office:");
for (String[] officeData : office) {
System.out.println(Arrays.toString(officeData));
}

// Display main[][]
System.out.println("Displaying main:");
for (String[] mainData : main) {
System.out.println(Arrays.toString(mainData));
}
}
}

输出:

Displaying office:
[-92.48392883, 52.96531732]
[-2.483984994, 92.48392883]
Displaying main:
[-1.207614869, 52.98908196]

注释:

  1. \\s+ 用于在空格上分割行。
  2. 使用try-with-resources语法来简化您的代码。

关于java - 读取文本文件,然后将其拆分为不同的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61549525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com