在Java FX应用程序中加载txt文件时catch中的IOException

时间:2017-01-14 23:18:58

标签: java exception javafx io

运行此代码后,我始终会打印Exception happened while loading 'Sokoban.txt',这意味着始终会捕获IOException。 我试图将Java项目转换为Java FX应用程序,并且不明白为什么加载txt文件不再适用于此。 我会很感激任何提示或帮助

package sokobangame;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class Sokobangame extends Application {

private final static int X = 0;
private final static int Y = 1;

private final static char WALL = '#';
private final static char PLAYER = '@';
private final static char BOX = '$';
private final static char GOAL = '.';
private final static char PLAYER_ON_GOAL = '+';
private final static char BOX_ON_GOAL = '*';
private final static char FREE = ' ';

private final static int[] UP = {0, -1};
private final static int[] DOWN = {0, 1};
private final static int[] LEFT = {-1, 0};
private final static int[] RIGHT = {1, 0};

private static char[][] room;
private static int freeBox;
private static int emptyGoal;

private static int[] size = {-1, 0};
private static int[] player;
public static String file = "sokoban.txt";

/**
 * Loads the level from the "file" and validate it
 *
 * @param file path to the file
 * @return false iff an error occurs or the level is invalid, true otherwise
 */
private static boolean loadLevel(String file) {
    BufferedReader bufferedReader;
    try {
        bufferedReader = Files.newBufferedReader(Paths.get(file));
        bufferedReader.mark(100 * 100);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
             System.out.println("line = bufferedReader.readLine()) != null");

            size[Y]++;
            if (size[X] > -1 && size[X] != line.length()) {
                return false;
            } else {
                size[X] = line.length();
            }
        }

        bufferedReader.reset();
        room = new char[size[Y]][];

        int i = 0;
        while ((line = bufferedReader.readLine()) != null) {
            room[i] = new char[line.length()];
            for (int j = 0; j < line.length(); j++) {
                room[i][j] = line.charAt(j);
            }
            i++;
            // oder room[i++] = line.toCharArray();
        }
        bufferedReader.close();
    } 
    catch (IOException e) {
        System.out.println("Exception happened while loading 'Sokoban.txt'");
        return false;
    }

    for (int i = 0; i < room.length; i++) {
        for (int j = 0; j < room[i].length; j++) {
            switch (room[i][j]) {
                case FREE:
                case BOX_ON_GOAL:
                case WALL:
                    break;
                case PLAYER_ON_GOAL:
                    emptyGoal++;
                case PLAYER:
                    if (player != null) {
                        return false;
                    } else {
                        player = new int[]{j, i};
                    }
                    break;
                case BOX:
                    freeBox++;
                    break;
                case GOAL:
                    emptyGoal++;
                    break;
                default:
                    return false;
            }
        }
    }
    return !(player == null || emptyGoal != freeBox);
}

/**
 * Prints the level to the output stream
 */
private static void printLevel() {
    for (char[] row : room) {
        System.out.println(row);
    }
}

/**
 * Function for vector addition
 *
 * @param first first vector
 * @param second second vector
 * @return new vector = first + second
 */
private static int[] add(int[] first, int[] second) {
    return new int[]{first[X] + second[X], first[Y] + second[Y]};
}

/**
 * Game logic for Sokoban
 *
 * @return true iff the level was solved, otherwise false
 */
private static boolean game() {
    // create new Scanner that reads from console
    Scanner input = new Scanner(System.in);

    // flag if we quit the program
    boolean run = true;
    int[] direction;
    do {
        printLevel();
        System.out.println("Do you want to go up, down, left, right or exit the program?");

        // check which command was chosen and execute it
        switch (input.next()) {
            case "w":
            case "up":
                direction = UP;
                break;
            case "s":
            case "down":
                direction = DOWN;
                break;
            case "a":
            case "left":
                direction = LEFT;
                break;
            case "d":
            case "right":
                direction = RIGHT;
                break;
            case "exit":
                run = false;
                continue;
            default: // if the user input is not one of our commands print help
                System.out.println("Command unknown! Please type up, down, left or right to move or exit to quit this program");
                continue;
        }

        if (!move(direction)) {
            System.out.println("You can not go there!");
        }
    } while (run && emptyGoal != 0 && freeBox != 0);
    return run;
}

/**
 * Makes a move
 *
 * @param direction as a vector
 * @return true iff it was successful, otherwise false
 */
private static boolean move(int[] direction) {
    int[] next = add(player, direction);

    switch (room[next[Y]][next[X]]) {
        case BOX_ON_GOAL:
        case BOX:
            int[] behind = add(next, direction);
            if (!(room[behind[Y]][behind[X]] == FREE || room[behind[Y]][behind[X]] == GOAL)) {
                return false;
            }

            if (room[next[Y]][next[X]] == BOX_ON_GOAL) {
                emptyGoal++;
                freeBox++;
            }

            if (room[behind[Y]][behind[X]] == GOAL) {
                room[behind[Y]][behind[X]] = BOX_ON_GOAL;
                emptyGoal--;
                freeBox--;
            } else {
                room[behind[Y]][behind[X]] = BOX;
            }

            if (room[next[Y]][next[X]] == BOX_ON_GOAL) {
                room[next[Y]][next[X]] = GOAL;
            } else {
                room[next[Y]][next[X]] = FREE;
            }
        case GOAL:
        case FREE:
            if (room[player[Y]][player[X]] == PLAYER_ON_GOAL) {
                room[player[Y]][player[X]] = GOAL;
            } else {
                room[player[Y]][player[X]] = FREE;
            }

            player = next;

            if (room[player[Y]][player[X]] == FREE) {
                room[player[Y]][player[X]] = PLAYER;
            } else {
                room[player[Y]][player[X]] = PLAYER_ON_GOAL;
            }
            return true;
        default:
            return false;
    }
}

@Override
public void start(Stage primaryStage) {

    if (!loadLevel(file)) {
        System.err.println("Level has an invalid format");
        return;
    }
    if (game()) {
        System.out.println("Yeah you have solved the level :)");
    } else {
        System.out.println("You have not solved the level :(");
    }
    printLevel();
    System.out.println("Goodbye");

}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    if (args.length > 0) {
        file = args[0];

    }
    launch(args);
}
}

编辑:运行输出

  

ant -f C:\ Users \ Nouri \ Desktop \ Sokobangame jfxsa-run       在里面:       删除:C:\ Users \ Nouri \ Desktop \ Sokobangame \ build \ built-jar.properties       DEPS-JAR:       更新属性文件:C:\ Users \ Nouri \ Desktop \ Sokobangame \ build \ built-jar.properties       编译:       检测到JavaFX Ant API版本1.3       JFX-部署:       罐:       将12个文件复制到C:\ Users \ Nouri \ Desktop \ Sokobangame \ dist \ run822624664       JFX-项目运行:       执行C:\ Users \ Nouri \ Desktop \ Sokobangame \ dist \ run822624664 \ Sokobangame.jar   使用平台C:\ Program Files \ Java \ jdk1.8.0_91 \ jre / bin / java       加载&#S; Sokoban.txt&#39;       级别格式无效

编辑2:

    catch (IOException e) {
        System.out.println("Exception happened while loading 'Sokoban.txt'");
        e.printStackTrace();
        return false;
    }

运行输出:

  

C:\ Users \ Nouri&gt; cd C:\ Users \ Nouri \ Desktop \ Sokobangame \ dist

     

C:\ Users \ Nouri \ Desktop \ Sokobangame \ dist&gt; java -jar Sokobangame.jar   加载&#S; Sokoban.txt&#39;   java.nio.file.NoSuchFileException:sokoban.txt           at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)           at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)           at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)           at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)           at java.nio.file.Files.newByteChannel(Unknown Source)           at java.nio.file.Files.newByteChannel(Unknown Source)           at java.nio.file.spi.FileSystemProvider.newInputStream(Unknown Source)           at java.nio.file.Files.newInputStream(Unknown Source)           at java.nio.file.Files.newBufferedReader(Unknown Source)           at java.nio.file.Files.newBufferedReader(Unknown Source)           在sokobangame.Sokobangame.loadLevel(Sokobangame.java:52)           在sokobangame.Sokobangame.start(Sokobangame.java:243)           at com.sun.javafx.application.LauncherImpl.lambda $ launchApplication1 $ 162(LauncherImpl.java:863)           at com.sun.javafx.application.PlatformImpl.lambda $ runAndWait $ 175(PlatformImpl.java:326)           at com.sun.javafx.application.PlatformImpl.lambda $ null $ 173(PlatformImpl.java:295)           at java.security.AccessController.doPrivileged(Native Method)           at com.sun.javafx.application.PlatformImpl.lambda $ runLater $ 174(PlatformImpl.java:294)           at com.sun.glass.ui.InvokeLaterDispatcher $ Future.run(InvokeLaterDispatcher.java:95)           at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)           at com.sun.glass.ui.win.WinApplication.lambda $ null $ 148(WinApplication.java:191)           at java.lang.Thread.run(Unknown Source)Level的格式无效

1 个答案:

答案 0 :(得分:0)

你得到的NoSuchFileException异常对于问题是非常自我解释的。

通过执行以下操作,您可以为要加载的文件使用硬编码路径:

$wsdl = 'http://www.webservicex.net/geoipservice.asmx?WSDL';
// you can get the NS from the wsdl
$wsdlNS = "http://www.webservicex.net/";

$client = new SoapClient($wsdl, array('trace'=>1));
$IPAddress = new SoapVar('198.252.206.16', XSD_STRING, null, null, 'IPAddress', $wsdlNS);
$GetGeoIP = new SoapVar(['IPAddress' => $IPAddress], SOAP_ENC_OBJECT, 'GetGeoIP', null, 'GetGeoIP', $wsdlNS);
$response = $client->GetGeoIP($GetGeoIP);

var_dump($response);

在您的主要版本中,您尝试从命令行参数中获取文件。保留变量unitialized并以这种方式执行,或者使用正确的内容初始化路径变量。

还有其他一些提示。您打开一个BufferedReader,在操作结束时关闭它。关闭读取最好在finally块中移动。这是一个好主意,即使发生异常,也要确保资源关闭。理想情况下,因为您使用java.nio.files。*,您可以使用try-with-resources语句自动关闭它们,以确保您的资源始终处于关闭状态。