我想将文本文件转换为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 文件打开?
最佳答案
好吧,如果不真正了解 addFileTag() 方法正在做什么,就很难判断。我能想到的唯一原因是 webPage.txt 文件仍然打开以进行读取或写入操作。
您的代码已访问该文件,但从未再次关闭它。您无法重命名打开的文件。我不得不假设这实际上是在 addFileTag() 方法中的某个地方完成的。
由于您对 File.renameTo() 方法的调用不成功,因此“webPage.txt”文本文件从未重命名为“CompiledWebpage.html”,因此本质上系统中根本不存在“CompiledWebpage.html”文件。但这并不是 Windows NotePad 应用程序打开您的文件而不是预期的默认 Web 浏览器的原因:
首先,声明并初始化了名为“file”的文件对象变量,并将其初始化为与“D:/dc1000/Project/webPage.txt”相关 文本文件,并且它总是如此,因为它是全局类,当然除非该关系在代码中的某处发生更改。坦率地说...事实并非如此,我想现在这是一件好事,因为如果您的文件重命名成功,您只会得到一个 FileNotFound 异常,因为文本文件与 ' file'变量将不再存在,因为它被重命名了。
您真正想要传递给 DeskTop.browse() 方法的是 File 对象“file2”变量,该变量与“D:/dc1000/Project/CompiledWebpage.html” 文本文件。请注意,您仍然会收到 FileNotFound 异常,因为 File.renameTo() 方法失败。因此,您肯定想确保自己在这里取得成功。
无论如何...为什么打开的是 Windows NotePad 应用程序而不是Web 浏览器?
原因如下:
操作系统文件关联决定了使用 DeskTop.browse() 方法时哪个应用程序将打开文件。在Windows操作系统中,默认情况下会自动在记事本中打开并显示扩展名为“.txt”的文件,该文件扩展名为“.txt” “.docx”自动打开并显示在MS Office WORD中,打开文件扩展名为“.html”的文件并显示在默认的网络浏览器中。我想你明白了。
因为“file”变量仍然与文件“D:/dc1000/Project/webPage.txt”相关,并且 File.renameTo() 方法失败,Windows 仅看到 .txt 文件扩展名并将该文件(按照“file”变量中的规定)显示到 NotePad 。
那么...我怎样才能让这一切真正发挥作用!?
好吧,如果我可以如此大胆,请改为这样做:
将其放在代码中的某个位置,按钮操作事件或其他任何位置:
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;
}
}
好吧,我希望这对您有所帮助,或者至少是有趣的。
关于Java:使用 File.renameTo() 使用浏览器将文本文件打开为 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34883774/