我必须编写一个程序,用户选择一个.java文件,程序会创建一个html文件,并将所有代码写入其中,添加必要的HTML标记,以便正确显示。无论我怎么想并在网上找到我都无法正确地做到这一点,唯一能写的就是那些我创建的字符串中的HTML标签。
它运行,用户可以选择文件并选择保存位置。文件本身已创建,但.java文件中的所有信息都不会进入.html文件。
package convertjavahtml;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.filechooser.*;
import static jdk.nashorn.internal.runtime.ScriptingFunctions.readLine;
public class ConvertJavaHTML {
public static void main(String[] args) throws IOException{
String name = null;
String newname = null;
try {
FileNameExtensionFilter filter = new FileNameExtensionFilter("Java", "java");
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
name = file.getName();
newname = name.substring(0, name.indexOf("."));
}
FileNameExtensionFilter filter2 = new FileNameExtensionFilter("html files (*.html)", "html");
JFileChooser saver = new JFileChooser();
saver.setFileFilter(filter2);
saver.setSelectedFile(new File(newname));
int returnVal2;
returnVal2 = saver.showSaveDialog(null);
int response = 0;
if(returnVal2 == JFileChooser.APPROVE_OPTION)
{
FileWriter write = new FileWriter(saver.getSelectedFile()+".html");
write.close();
}
File file = new File(name);
Scanner scanner = new Scanner(file);
String beg = "<h2>Demo.java</h2>\n<html>\n<pre>\n<body>\n";
String end = "\n</body>\n</pre>\n</html>";
PrintWriter out = new PrintWriter(new File(newname + ".html"));
out.println(beg);
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(chooser.getName(file)))) {
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(newname), "utf-8"))) {
writer.write(readLine);
}
}
}
out.print(end);
out.flush();
out.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
private static char handleFile(File file, Charset encoding) throws IOException {
try
(InputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in, encoding);
Reader buffer = new BufferedReader(reader)){
return handleChars(buffer);
}
}
private static char handleChars(Reader reader) throws IOException {
int r;
while((r = reader.read()) != -1)
{
char ch = (char) r;
System.out.println(ch + " ");
}
return 0;
}
}