【问题标题】:Read a file and check if lines are equal to a String读取文件并检查行是否等于字符串
【发布时间】:2018-07-30 08:39:49
【问题描述】:

我的代码应该彻底解释我的问题。我需要读取整个文件并获取每一行的数据,然后应用该数据。我在读取整个文件并获取每行数据时遇到问题。它还将整个程序发送到一个无限循环中。我添加了一些发送到控制台的调试消息。这就是“Logger.log(”)”的含义。他们正在向控制台发送调试消息。这是我的代码:

编辑:我通过将“while (fileList.length != 0)”更改为“if (fileList.length != 0)”解决了循环问题,但现在出现了在调试消息之后无法继续操作的问题“记录器.log("14")"。

public void setItems(Inventory inv)
{
    try
    {
        if (!kit.getDataFolder().exists())
        {
            kit.getDataFolder().mkdirs();
        }

        Logger.log("1");

        File folder = files.getFolder("GUI Menu");
        Logger.log("2");
        if (!folder.exists())
        {
            files.createFolder("GUI Menu");
        }
        File[] fileList = folder.listFiles();
        Logger.log("3");
        if (fileList.length != 0)
        {
            Logger.log("4");
            for (File forFile : fileList)
            {
                Logger.log("5");
                File file = files.getGuiItem(forFile);
                Logger.log("6");
                if (!file.exists())
                {
                    Logger.log("Cannot open Inventory for the file");
                    return;
                }
                Logger.log("7");
                BufferedReader br = new BufferedReader(new FileReader(file));
                Logger.log("8");
                String line;
                Logger.log("9");
                while ((line = br.readLine()) != null)
                {
                    Logger.log("10");
                    ItemStack item;

                    if (line.contains("Item ID: "))
                    {
                        Logger.log("11");
                        String[] tSplit = line.split(": ");
                        String split = tSplit[1];
                        Logger.log("12");
                        if (StringCheck.isInteger(split))
                        {
                            Logger.log("13");
                            Material mat = Material.matchMaterial(split);

                            ItemStack item1 = new ItemStack(mat, 1);
                            item = item1;
                            Logger.log("14");

                            if (line.contains("Kit Name: "))
                            {
                                String[] jSplit = line.split(": ");
                                String j2split = jSplit[1];
                                Logger.log("15");

                                if (item != null && !item.equals(Material.AIR))
                                {
                                    ItemMeta meta = item.getItemMeta();

                                    meta.setDisplayName(Color.add("&6" + j2split + "&e Kit"));
                                    item.setItemMeta(meta);
                                    Logger.log("16");

                                    if (line.contains("Price: "))
                                    {
                                        String[] pSplit = line.split(": ");
                                        String p2split = pSplit[1];
                                        Logger.log("17");

                                        if (item != null && !item.equals(Material.AIR))
                                        {
                                            this.setLore(item, "&ePrice: &6" + p2split);

                                            if (line.contains("Slot Number: "))
                                            {
                                                Logger.log("18");
                                                String[] fSplit = line.split(": ");
                                                String f2split = fSplit[1];
                                                if (StringCheck.isInteger(f2split))
                                                {
                                                    Logger.log("19");
                                                    if (item != null && !item.equals(Material.AIR))
                                                    {
                                                        Logger.log("20");
                                                        if (inv.getItem(Integer.parseInt(split)) == null || inv.getItem(Integer.parseInt(split)).equals(Material.AIR))
                                                        {
                                                            inv.setItem(Integer.parseInt(split), item);
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                br.close();
            }
        }
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}

【问题讨论】:

  • while (fileList.length != 0) 应该是if 声明
  • 嗯,这能解决我的问题吗?
  • 它将 1- 使其更具可读性和 2- 降低陷入无限循环的风险
  • 好的,改了。还有什么你可以发现的错误吗?
  • 我仍然不知道您为什么同时使用BufferedReaderScanner。我还鼓励您使用try-with-resources statement 来更好地管理您的资源

标签: java file minecraft reader


【解决方案1】:

使用Scanner 时,您需要的方法是hasNextLine()nextLine()。当您阅读完所有行后,方法hasNextLine() 将返回false。如果使用BufferedReader,您必须通过检查读取该行的结果来检查您是否没有耗尽输入。无论您使用哪种文件阅读方法,都必须确保关闭阅读器。这里我给大家举个更复杂的BufferedReader例子,用try-with-resourcesclose()吧。喜欢,

File file = new File("test.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
        // ...
    }
} catch (IOException e) {
    e.printStackTrace();
}

为了完整起见,使用Scanner

File file = new File("test.txt");
try (Scanner scanner = new Scanner(file)) {
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        // ...
    }
} catch (IOException e) {
    e.printStackTrace();
}

使用正则表达式解析每一行,

Pattern p = Pattern.compile("Slot Number: (\\d+) Kit Name: (\\S+) Price: (\\d+) Item ID: (\\d+)",
        Pattern.CASE_INSENSITIVE);
String line = "Slot Number: 0 Kit Name: Basic Price: 50 Item ID: 385";
Matcher m = p.matcher(line);
if (m.matches()) {
    int slot = Integer.parseInt(m.group(1));
    String name = m.group(2);
    int price = Integer.parseInt(m.group(3));
    int id = Integer.parseInt(m.group(4));
    System.out.printf("%s %d %d %d%n", name, id, slot, price);
}

哪些输出

Basic 385 0 50

【讨论】:

  • 我不确定这是否能回答我的问题。我需要获取文件中的所有数据。文件如下所示: 插槽编号:0 套件名称:基本价格:50 物品 ID:385
  • @CodaPlays 将您的代码用于处理我拥有// ... 的每一行;这两个示例都将获取文件中的所有数据。我没有,也不打算为您编写解析代码。但我建议你使用 正则表达式 Pattern.
  • 当我将代码粘贴到我的问题中时,我忘记删除我正在测试的代码。这就是扫描仪在那里的原因。我已经编辑了我的问题代码。你认为我现在的代码会起作用吗?
  • 试试代码。不要编辑您的问题以包含我的答案;特别是因为我的回答是:“如何读取文件中的每一行”...
  • 好的,抱歉。我是 StackOverflow 的新手,所以请原谅我的无知。代码现在可以正常工作,但没有超过代码中的“Logger.log(”14)”行。它只是停在那里。你知道原因吗?
【解决方案2】:

根据您对另一个答案的评论(Elliot 的,这是完全正确的),我将为您提供一些关于一种易于遵循/理解的方法来做您想做的事情的指示。

  1. 使用 Elliot 回答中的任一实现。
  2. 创建一个接受String(文件中的一行)并将其转换为您需要的任何内容的方法。
  3. 在 Elliot 的代码中,将 // ... 行替换为对您创建的方法的调用,并传入您刚刚从文件中读取的行

这将使您的文件读取代码非常漂亮和干净,并且还可以使其易于阅读。如果需要,您还可以通过再次调用该方法在其他地方重用该代码。如果您不知道如何解析文件并从中获取您想要的信息,我建议您在 SO 上提出另一个问题。

【讨论】:

  • 好的,谢谢您的礼貌回答。您建议的内容是否会针对我正在调用的文件夹中的每个文件运行?
  • 如果你想读取很多文件,我建议将每个文件名添加到一个数组中,然后在循环中创建一个文件对象,从数组基于循环的当前迭代。然后,在创建文件对象和某种阅读器的循环内,放置从单个文件中读取的代码。从数组中读入适当的文件名。为该文件创建一个阅读器。逐行读取文件。重复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
  • 2020-06-09
  • 1970-01-01
  • 2016-12-21
  • 2019-10-10
  • 2015-02-04
  • 1970-01-01
相关资源
最近更新 更多