简单

wh6knrhe  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(301)

首先,我对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\时间线.html
非常感谢您的帮助!
编辑:我想出来了。。我只是想让它看一个数组,而不是指定哪个数组。糟糕的代码实践,我知道,但简单的解决方法是:
string htmlfilepath=specifiedlocation+“\timeline.html”;

string htmlfilepath=specifiedlocation[0]+“\timeline.html”;
很抱歉发了一篇愚蠢的帖子。。。

ldfqzlk8

ldfqzlk81#

替换此

String htmlFilePath = specifiedLocation + "\\Timeline.html";

StringBuilder htmlFilePath= new StringBuilder();
   for(String s : specifiedLocation)
      htmlFilePath.append(s) ;
   htmlFilePath.append( "\\Timeline.html" );

你也可以使用 Arrays.toString(specifiedLocation) 更多信息

67up9zun

67up9zun2#

这个 toString 方法 Array 不重写。它会给你一个 String 数组的表示(这是什么 toStringObject 包含对象的类型(数组)+“@”+其哈希代码。
如果希望输出更好,请使用 Arrays.toString 相反。但这仍然给你 [ s、 因此,基于循环的临时解决方案可能更好。另外,如果要连接 String s、 使用 StringBuilder 可以更快。
另见(无耻升职)我对另一个问题的回答。

相关问题