【问题标题】:Reading from a file and storing into an array从文件中读取并存储到数组中
【发布时间】:2021-03-17 21:27:39
【问题描述】:

我有一个正在处理的项目是一个迷宫求解器,但我试图找出从文件中读取的内容并将其存储到数组中。我所查找的大多数东西,它们在程序中使用他们创建的数组,而我的需要我从文件中读取并从那里构造它。到目前为止,我有这个:

       File map = new File("/Users/michelmaza/Downloads/Project1Map.txt"); //create an object of the file we are reading in
       Scanner scanner = new Scanner(map); //create scanner to read file in
       LinkedList<String> mapping = new LinkedList<String>();//create array list to store the reading from the file

       while (scanner.hasNextLine()) {
            mapping.add(scanner.nextLine()); //Stores the file into the string where every 10 number is a new line
        }
        System.out.println(mapping); //test to see if it works.
        scanner.close(); //close the scanner since its not used anymore.
        } 
        catch (FileNotFoundException e) { //catch in case the file is not found.
        System.out.println("There was no file found, please try again.");
        e.printStackTrace();
        }

当我输出它时,它会将整个数组排成一行,但我试图获得基本上是 10x10 网格的地图格式。欢迎任何有关如何解决此问题的提示或建议。

现在的输出 [2 3 3 0 0 0 1 0 0 3, 3 0 0 0 0 0 0 3 0 3, 3 3 0 0 0 0 3 3 0 3, 3 3 0 0 0 0 0 0 0 0, 3 3 0 0 0 0 3 3 3 3, 3 3 0 0 0 3 3 3 3 3, 3 3 0 0 3 3 3 3 3 3, 3 3 0 0 3 3 3 3 3 3, 3 3 0 0 3 3 3 3 3 3, 3 3 3 2 3 3 3 3 3 3]

想要的输出是

{2, 3, 3, 0, 0, 0, 1, 0, 0, 3},
{3, 0, 0, 0, 0, 0, 0, 3, 0, 3},
{3, 3, 0, 0, 0, 0, 3, 3, 0, 3},
{3, 3, 0, 0, 0, 0, 0, 0, 0, 0},
{3, 3, 0, 0, 0, 0, 3, 3, 3, 3},
{3, 3, 0, 0, 0, 3, 3, 3, 3, 3},
{3, 3, 0, 0, 3, 3, 3, 3, 3, 3},
{3, 3, 0, 0, 3, 3, 3, 3, 3, 3},
{3, 3, 0, 0, 3, 3, 3, 3, 3, 3},
{3, 3, 3, 2, 3, 3, 3, 3, 3, 3}

【问题讨论】:

  • 我认为只是您隐式使用了 LinkedList 的 toString 方法,该方法会将每个元素显示在同一行上。答案可能是遍历列表(或使用流)并打印每个元素(其中每个元素是文件中一行的 10 个数字集合之一)

标签: java arrays arraylist


【解决方案1】:

由于我不清楚您的输入文件和预期输出,所以我专注于阅读文件,我希望每行已经有 10 个字符串,并且有 10 行给你你的网格

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

class Scratch {
    public static void main(String[] args) throws IOException {
        List<String> allLinesInFile = Files.readAllLines(Paths.get("/tmp/maze.input"));
        String[] asArray = allLinesInFile.toArray(new String[0]);
        System.out.println(Arrays.toString(asArray));
    }
}

更新: 既然现在输入和输出都清楚了,这里是完整的代码:)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.*;

class Scratch {
    public static void main(String[] args) throws IOException {
        Path mazeInputFile = Paths.get("/tmp/maze.input");
        Files.writeString(mazeInputFile, "2 3 3 0 0 0 1 0 0 3\n", StandardOpenOption.TRUNCATE_EXISTING);
        Files.writeString(mazeInputFile, "3 0 0 0 0 0 0 3 0 3\n", StandardOpenOption.APPEND);
        Files.writeString(mazeInputFile, "3 3 0 0 0 0 3 3 0 3\n", StandardOpenOption.APPEND);
        Files.writeString(mazeInputFile, "3 3 0 0 0 0 0 0 0 0\n", StandardOpenOption.APPEND);
        Files.writeString(mazeInputFile, "3 3 0 0 0 0 3 3 3 3\n", StandardOpenOption.APPEND);
        Files.writeString(mazeInputFile, "3 3 0 0 0 3 3 3 3 3\n", StandardOpenOption.APPEND);
        Files.writeString(mazeInputFile, "3 3 0 0 3 3 3 3 3 3\n", StandardOpenOption.APPEND);
        Files.writeString(mazeInputFile, "3 3 0 0 3 3 3 3 3 3\n", StandardOpenOption.APPEND);
        Files.writeString(mazeInputFile, "3 3 0 0 3 3 3 3 3 3\n", StandardOpenOption.APPEND);
        Files.writeString(mazeInputFile, "3 3 3 2 3 3 3 3 3 3\n", StandardOpenOption.APPEND);

        System.out.printf("Wrote mazeInputFile = %s\n", mazeInputFile);

        System.out.printf("Reading all Lines From Input file : %s\n", mazeInputFile);
        String[][] mazeInputArray = Files.lines(mazeInputFile) // Gives The lines in file as a Stream
                .filter(line -> line != null && !line.isBlank()) // Filter out unwanted Lines
                .map(line -> line.split(" ", 10)) // Split the line by Space with a maximum of 10 columns
                .toArray(String[][]::new); // Collect as a 2 dimensional Array
        System.out.println("-- --");


        System.out.println("-- Print the Array using a Java 8 Streams (my preference) --");
        String printableMaze = java.util.Arrays.stream(mazeInputArray).
                map(rows -> java.util.Arrays.stream(rows).
                        map(row -> String.join(",", row)). // join each row with a comma
                        collect(joining(",", "{", "}"))). // surround the row with a prefix { and suffix } and join the columns with a comma
                collect(joining(",\n")); // join each row with a leading comma and a newline
        System.out.printf("%s\n", printableMaze);
        System.out.println("-- --");
        System.out.println("-- Here, actually the reading of the file and printing can be combined to read huge files as well without taking too much memory --");
        System.out.println("-- --");

        System.out.println("-- Print the Array using good old for each loops, code looks kind of better but last comma remains --");
        for (String[] rows : mazeInputArray) {
            System.out.print("{");
            System.out.print(String.join(",", rows));
            System.out.print("},\n"); // needs ugly imperative code to get rid of the last comma :P
        }
        System.out.println("-- --");
    }
}

输出看起来像

Wrote mazeInputFile = /tmp/maze.input
Reading all Lines From Input file : /tmp/maze.input
-- --
-- Print the Array using a Java 8 Streams (my preference) --
{2,3,3,0,0,0,1,0,0,3},
{3,0,0,0,0,0,0,3,0,3},
{3,3,0,0,0,0,3,3,0,3},
{3,3,0,0,0,0,0,0,0,0},
{3,3,0,0,0,0,3,3,3,3},
{3,3,0,0,0,3,3,3,3,3},
{3,3,0,0,3,3,3,3,3,3},
{3,3,0,0,3,3,3,3,3,3},
{3,3,0,0,3,3,3,3,3,3},
{3,3,3,2,3,3,3,3,3,3}
-- --
-- Here, actually the reading of the file and printing can be combined to read huge files as well without taking too much memory --
-- --
-- Print the Array using good old for each loops, code looks kind of better but last comma remains --
{2,3,3,0,0,0,1,0,0,3},
{3,0,0,0,0,0,0,3,0,3},
{3,3,0,0,0,0,3,3,0,3},
{3,3,0,0,0,0,0,0,0,0},
{3,3,0,0,0,0,3,3,3,3},
{3,3,0,0,0,3,3,3,3,3},
{3,3,0,0,3,3,3,3,3,3},
{3,3,0,0,3,3,3,3,3,3},
{3,3,0,0,3,3,3,3,3,3},
{3,3,3,2,3,3,3,3,3,3},
-- --

Process finished with exit code 0
  • 我不确定您要做什么,但打印它与处理它不同。
  • 我之所以将其分开,是因为您可以简单地使用 mazeInputArray 来对输入进行实际操作
  • 打印是一种 PIA,使用流可以更轻松地不考虑边缘情况,因为它们是智能/隐式处理的。

【讨论】:

  • 是的,文件已经是 10 行 10 个字符的格式
  • 然后试一试,这会将文件中的所有行读入List&lt;String&gt;,然后您可以拆分每一行以获取列。无需摆弄 Scanner 和 FIle,Java NIO 非常好,尤其是在读取整个文件并且它不是一个巨大的文件(如 TB 大小)时
  • 它的输出几乎和以前一样,但是你说我可以拆分行,我该怎么做?提前致谢!
  • 您能否使用示例输入文件和预期的示例输出发布/更新原始问题?那么测试起来要容易得多:)它不必是整个文件,只需 2 行和相应的输出预期
  • 我刚刚更新了我得到的和想要得到的,谢谢!
【解决方案2】:

您好,我为您的问题写了一个小例子。希望对你有用。

在map.txt中

2 3 3 0 0 0 1 0 0 3 3 0 0 0 0 0 0 3 0 3 3 3 0 0 0 0 3 3 0 3 3 3 0 0 0 0 0 0 0 0 3 3 0 0 0 0 3 3 3 3 3 3 0 0 0 3 3 3 3 3 3 3 0 0 3 3 3 3 3 3 3 3 0 0 3 3 3 3 3 3 3 3 0 0 3 3 3 3 3 3 3 3 3 2 3 3 3 3 3 3

代码:

public static void main(String[] args) {
    final int mapSize = 10;
    List<List<String>> map = new ArrayList<>();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader("F:\\map.txt"));
        String line = reader.readLine();
        if(line != null && !line.isEmpty()) {
            for (int i = 0; i < mapSize; i++) {
                map.add(i, new ArrayList<>());
                String substring = line.trim().substring(0, mapSize * 2 - 1); // 2 for whitespaces
                line = line.trim().substring(mapSize * 2 - 1);
                map.get(i).addAll(Arrays.asList(substring.split(" ")));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    for(List<String> row : map) {
        System.out.println(String.join(",", row));
    }
}

输出:

2,3,3,0,0,0,1,0,0,3
3,0,0,0,0,0,0,3,0,3
3,3,0,0,0,0,3,3,0,3
3,3,0,0,0,0,0,0,0,0
3,3,0,0,0,0,3,3,3,3
3,3,0,0,0,3,3,3,3,3
3,3,0,0,3,3,3,3,3,3
3,3,0,0,3,3,3,3,3,3
3,3,0,0,3,3,3,3,3,3
3,3,3,2,3,3,3,3,3,3

【讨论】:

  • 我想我需要展示我正在尝试做的事情。所以我的 .txt 文件是这样的...... 2 3 3 0 0 0 1 0 0 3 3 0 0 0 0 0 0 3 0 3 3 3 0 0 0 0 3 3 0 3 3 3 0 0 0 0 0 0 0 0 3 3 0 0 0 0 3 3 3 3 3 3 0 0 0 3 3 3 3 3 3 3 0 0 3 3 3 3 3 3 3 3 0 0 3 3 3 3 3 3 3 3 0 0 3 3 3 3 3 3 3 3 3 2 3 3 3 3 3 3 其中 1 = 起点 2 = 终点 3 = 墙壁 0 = 开放路径 所以当我的代码读取它时,它显示为一条直线,但我试图让它是一个 10x10 的网格,据我所见,它使每一行都成为一个数组,这就是我想要做的,希望这会有所帮助!谢谢
  • @MichelMazaL 我根据您的情况重新安排了我的解决方案。你能再检查一下吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
  • 2015-07-01
  • 2015-01-22
  • 1970-01-01
相关资源
最近更新 更多