首先,我对 Java 还很菜鸟,所以我想这个问题可以很容易回答。
我有一个程序,首次启动时,会在指定位置(C 驱动器上的 AppData 文件夹)查找名为 location.txt 的文件,如果该文件不存在,则会创建它。该文件最终将只有一个从 JFileChooser 中选择的文件路径。
我希望我的程序读取此文本文件中的文件路径,这样我就不必静态引用文件位置。不过我现在遇到了问题。这是一些代码:(不要介意糟糕的代码间距,stackoverflow 对我来说很难)
BufferedReader bufferedReader = new BufferedReader(fileReader); // creates the buffered reader for the file
java.util.List<String> lines = new ArrayList<String>(); //sets up an ArrayList (dynamic no set length)
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) { // reads the file into the ArrayList line by line
lines.add(line);
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error 16: "+e.getMessage()+"\nPlease contact Shane for assistance.");
System.exit(1);
}
try {
bufferedReader.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error 17: "+e.getMessage()+"\nPlease contact Shane for assistance.");
System.exit(1);
}
String[] specifiedLocation = lines.toArray(new String[lines.size()]); // Converts the ArrayList into an Array.
String htmlFilePath = specifiedLocation + "\\Timeline.html";
File htmlFile = new File(htmlFilePath);
JOptionPane.showMessageDialog(null, specifiedLocation);
JOptionPane.showMessageDialog(null, htmlFilePath);
我不明白的是,为什么当弹出指定位置的消息对话框时,文件路径完美地存在。但是,当弹出 htmlFilePath 的消息对话框时,它看起来像这样:
[Ljava.lang.String;@1113708\Timeline.html
非常感谢任何帮助!
编辑: 我想通了..把头撞在 table 上我试图让它查看一个数组而不是指定哪个数组。我知道,代码实践不好,但简单的解决方法是采用以下方法:
字符串 htmlFilePath = 指定位置 + "\Timeline.html";
到
字符串 htmlFilePath = 指定位置[0] + "\Timeline.html";
抱歉发了这么愚蠢的帖子...
最佳答案
Array
的 toString
方法不会被覆盖。它将返回数组的 String
表示形式(这就是 Object
中的 toString
的作用),其中包括对象的类型(数组)+“@”+它的哈希码。
如果您希望输出更好,请改用Arrays.toString
。但这仍然为您提供了[
,因此基于循环的临时解决方案可能更好。另外,如果您要连接 String
,使用 StringBuilder
会更快。
还有see (无耻的推广)我对另一个问题的回答。
关于java - Bufferedreader 和文件路径 - 简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16949633/