开发者

Why won't the importing of a file work in my Java program?

开发者 https://www.devze.com 2023-01-24 17:05 出处:网络
I\'m not sure why this code won\'t allow me to choose a file and then scan it. How can I debug it? private String[][] importMaze(){

I'm not sure why this code won't allow me to choose a file and then scan it. How can I debug it?

private String[][] importMaze(){
    String fileName;
    JFileChooser fc = new JFileChooser();
    int returnVal = fc.showOpenDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
          fileName = fc.getSelectedFile().getName();

    File f = new File(fileName);
    try {
        Scanner scan = new Scanner(f);
        int rows = scan.nextInt();
        int columns = scan.nextInt();
        String [][] maze = new String[rows][columns];
        int r = 0;
        wh开发者_C百科ile(scan.hasNext() && r<=rows){
            for(int c = 0; c<=columns;c++){
                maze[r][c]=scan.next();
            }
            r++;
        }
        return maze;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
    return null;
}


I have tried your code and it gets to the point where the dialog opens and you can select a file.

I think your problem lies here:

if(returnVal == JFileChooser.APPROVE_OPTION) {
      fileName = fc.getSelectedFile().getName();

File f = new File(fileName);

The following code:

fileName = fc.getSelectedFile().getName();

returns only the NAME of the file, not the full file path. This in turn causes

File f = new File(fileName);

to not open the file you want it to, but to simple "create" (it does not actually create the file until you write it out) the file.

What you need to do is replace those three line with:

if(returnVal == JFileChooser.APPROVE_OPTION) {
  File f = fc.getSelectedFile();

That would make f reference the file you chose.

0

精彩评论

暂无评论...
验证码 换一张
取 消