【问题标题】:Java: open text file as html file with browser using File.renameTo()Java:使用 File.renameTo() 使用浏览器将文本文件作为 html 文件打开
【发布时间】:2016-04-25 08:07:35
【问题描述】:

我想将文本文件转换为 html 文件,然后用浏览器打开。我尝试使用file.renameTo() 将文本文件的扩展名重命名为.html,但重命名尝试总是失败并且file.renameTo() 总是返回false。因此,当我尝试用下面的方法打开文件时,文件是在记事本中打开的。

文件声明:

 private File file;

构造函数中的文件声明:

 file = new File("D:/dc1000/Project/webPage.txt");
 file.getParentFile().mkdirs();

无效的方法:

 public void compileWebpage(){
        File file2 = new File("D:/dc1000/Project/CompiledWebpage.html");
        file2.getParentFile().mkdirs();
        addFileTags("end"); //add ending tags like </body>
        boolean success = true;
        try{
            success = file.renameTo(file2);
        }catch (Exception e){
            System.out.println(e);
        }

        if(!success){
          System.out.println("webPage compilation failed.");
        }

        Desktop desktop = Desktop.getDesktop();
        try{
            desktop.browse(file.toURI());
        }catch (IOException e){
            e.printStackTrace();
        }
    }

不抛出异常,“网页编译失败”打印到控制台,然后记事本打开文件。该文件在记事本中打开时如下所示:

<html>
<head>
</head>
<body>
<p>hi</p>
</body>
</html>

为什么File.renameTo() 总是失败?如何在浏览器中将此文本文件作为 html 文件打开?

【问题讨论】:

    标签: java html file browser file-rename


    【解决方案1】:

    好吧,如果不真正知道 addFileTag() 方法在做什么,就很难说清楚。我能想到的唯一原因是 webPage.txt 文件仍可用于读取或写入操作。

    您的代码已访问该文件,但从未再次关闭它。您不能重命名打开的文件。我不得不假设这实际上是在 addFileTag() 方法中的某个地方完成的。

    由于您对 File.renameTo() 方法的调用未成功,因此“webPage.txt”文本文件从未重命名为“CompiledWebpage.html”,因此本质上系统中根本不存在“CompiledWebpage.html”文件。然而,这并不是 Windows NotePad 应用程序打开您的文件而不是预期的默认 Web 浏览器的原因:

    首先声明并初始化了名为“file”的文件对象变量,以便与“D:/dc1000/Project/webPage.txt”相关> 文本文件,它总是因为它是全局类,除非这种关系在你的代码中的某个地方发生了变化。坦率地说...不是,我想现在这是一件好事,因为如果您的文件重命名成功,您将简单地得到一个 FileNotFound Exception 因为文本文件与“文件'变量将不再存在,因为它被重命名了。

    您真正想要传递给 DeskTop.browse() 方法的是 File 对象 'file2' 变量,它与"D:/dc1000/Project/CompiledWebpage.html" 文本文件。请注意,您仍然会收到 FileNotFound Exception,因为 File.renameTo() 方法失败了。所以你肯定想确保你在这里取得成功。

    随便...为什么打开的是 Windows NotePad 应用程序而不是 Web 浏览器

    原因如下:

    操作系统文件关联决定了在使用 DeskTop.browse() 方法时哪个应用程序将打开文件。在Windows操作系统中,默认会自动打开一个后缀为".txt"的文件,并在记事本中显示一个后缀为".txt"的文件。 ".docx"".docx"自动打开并显示在MS Office WORD中,打开一个文件扩展名为".html"的文件并显示在默认的 Web 浏览器 中。我想你明白了。

    因为 'file' 变量仍然与文件 "D:/dc1000/Project/webPage.txt" 相关,并且因为 File.renameTo() 方法失败,Windows 只看到 .txt 文件扩展名并将文件(在“文件”变量中规定)显示到 记事本

    那么...我怎样才能让这一切真正发挥作用!?

    好吧,如果我可以这么大胆,那就这样做吧:

    将其放置在代码中的某个位置、按钮操作事件或其他任何地方:

    String sourceFile = "D:/dc1000/Project/webPage.txt";
    String destinationFile = "D:/dc1000/Project/CompiledWebpage.html";
    
    boolean success = CompileToWebPage(sourceFile, destinationFile, "This is My Head Text");
    if (success) {
        System.out.println("Text File Successfully Compiled!");
    }
    else {
        System.out.println("Text File Compilation FAILED!");
    }
    
    //Display our new file in the web Browser...
    try {    
        File htmlFile = new File(destinationFile);
        Desktop.getDesktop().browse(htmlFile.toURI());
    } catch (IOException ex) {}
    

    这是一个新的 CompileToWebPage() 方法:

    private static boolean CompileToWebPage(final String sourcefilePath, 
                            final String destinationFilePath, String... headText) {
        // headText is OPTIONAL.
        String headTxt = "";
        if (headText.length != 0) { headTxt = headText[0]; }
    
        //Read sourcefilePath file data into a String ArrayList...
        BufferedReader input;
        try {
            input = new BufferedReader(new FileReader(sourcefilePath));
            if (!input.ready()) { throw new IOException(); }
        } 
        catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\nThe supplied "
                        + "file path was not found!\n\n" + sourcefilePath, "File NotFound", 
                        JOptionPane.ERROR_MESSAGE);
            return false;
        }
        catch (IOException ex) {
            JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\nThe supplied "
                        + "file is not ready to be read!\n\n" + ex.getMessage(), "File Not Ready", 
                        JOptionPane.ERROR_MESSAGE);
            return false;
        }
    
        // Place required HTML Tags into String ArrayList
        ArrayList<String> txt = new ArrayList<>();
        txt.add("<html>");
        txt.add("<head>");
        txt.add(headTxt);
        txt.add("</head>");
        txt.add("<body>");
    
        // Read each line of the source text File and add
        // them to our String ArrayList...
        try {
            String str;
            while((str = input.readLine()) != null){
                txt.add("<p>" + str + "</p>");
            }
            input.close();
        } 
        catch (IOException ex) { 
            JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\n"
                    + "There was a problem reading the source Text from file!\n\n"
                    + ex.getMessage(), "File Read Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    
        // Place our HTML finishing Tags into our String ArrayList...
        txt.add("</body>");
        txt.add("</html>");
    
        // Write the String ArrayList to our supplied Destination 
        // File Path...
        try {
            FileWriter fw = new FileWriter(destinationFilePath);
            Writer output = new BufferedWriter(fw);
    
            for (int i = 0; i < txt.size(); i++) {
                // Some Windows applications (such as NotePad require
                // the \r tag for a new line to actually be accomplished
                // within a text file.
                output.write(txt.get(i) + "\r\n");
            }
            output.close();
            return true;
        } 
        catch (IOException ex) { 
            JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\n"
                    + "There was a problem writing the Compiled Web Text to file!\n"
                    + "Ensure that permissions are properly set.\n\n" + ex.getMessage(),
                    "File Write Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }
    

    嗯,我希望这对你有所帮助,或者至少是有趣的。

    【讨论】:

      猜你喜欢
      • 2011-11-09
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 2012-04-30
      相关资源
      最近更新 更多