【问题标题】:How to fix this 'java.io.FileNotFoundException'如何修复此“java.io.FileNotFoundException”
【发布时间】:2019-08-28 23:54:04
【问题描述】:

我的 RPG 在编译器中运行良好。它输入一个文件并使用扫描仪读取它,但是当我将它导出到“.jar”文件中时,它会抛出 FileNotFoundException。

我尝试将文件放在不同的位置。我尝试过使用不同的方式来调用文件。似乎没有任何效果。

package worldStuff;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class World {

    public static String[][] initWorld(String[][]array,String name) throws FileNotFoundException {
        int j = 0;
        String string;
        Scanner input = new Scanner(new File(name+".map"));
        while(j!=30) {
            string = input.nextLine();
            array[j] = string.split(",");
            j++;
        }
        input.close();
        return array;
    }

}

这是输入文件的方法。我需要一种方法让它在编译后不会出错。我正在使用 Eclipse IDE 并在此配置上导出:

【问题讨论】:

  • 尝试填充路径。
  • 您的 .map 文件是否打包在 .jar 文件中?
  • jar 中的对象不是文件,您不能使用文件 API 来读取它们。看getResourceAsStream

标签: java eclipse file-io executable-jar


【解决方案1】:

如果你有使用 Java8 的选项,这个怎么样:

public static void main( String[] args ) {
        try {
            String[][] output = initWorld( "E:\\Workspaces\\Production\\Test\\src\\test\\test" );
            for ( String[] o : output ) {
                if ( o == null || o.length == 0 ) { break; }
                System.out.println( "- " + o[0] );
            }
        } catch ( FileNotFoundException ex ) {
            ex.printStackTrace();
        }
    }

    public static String[][] initWorld( String name ) throws FileNotFoundException {

        String array[][] = new String[30][];
        try (Stream<String> stream = Files.lines(Paths.get(name))) {
            List<String> inputList = stream.collect(Collectors.toList());
            for ( int i = 0; i < 30 && i < inputList.size(); i++ ) {
                array[i] = inputList.get( i ).split( "," );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return array;
    }

这里的主要方法是 jsut 用于测试目的(打印每个初始化数组的第一个元素)。

另外,不需要将 String[][] 作为参数传递。

只需将 initWorld 参数替换为目标文件的路径(如果您在 Windows 上,请确保使用 \,\ 本身就是一个转义字符)。

希望对您有所帮助。

【讨论】:

  • 当我编译时,我仍然遇到问题。这是一个错误的文件路径吗? spawnWorld = World.initWorld("Resources/world/spawn.map");
  • 路径可能有效,但任何无法访问您电脑的人都不可能知道上面是否有任何东西。尝试使用您绝对知道存在的绝对路径,例如“C:\\whatever\\folder\\path\\spawn.map”,或者如果您使用的是 linux,例如“/home/yourhomefolder/dev/spawn.map”,只需确保它是指向 100% 存在的文件的绝对路径。
  • 但是,我会与其他人共享它,这样就无法在他们的计算机上运行。
  • 老兄......不要分享它,只是用它来测试你的代码......看看它是否适用于绝对路径,如果它确实从那里获取它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2010-12-22
  • 2011-12-30
  • 2021-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多