为什么在我的 Java 程序中无法导入文件?
我不确定为什么这段代码不允许我选择文件然后扫描它。我该如何调试它?
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;
while(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'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;
while(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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经尝试过您的代码,它会打开对话框,您可以选择一个文件。
我认为你的问题出在这里:
以下代码:
仅返回文件的名称,而不是完整的文件路径。这反过来会导致
不打开您想要的文件,而是简单地“创建”文件(直到您将其写出为止,它实际上不会创建文件)。
您需要做的是将这三行替换为:
这将使 f 引用您选择的文件。
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:
The following code:
returns only the NAME of the file, not the full file path. This in turn causes
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:
That would make f reference the file you chose.