读取多个文本文件,附加一些html标记,然后将其保存到java中用户选择的目录中

读取多个文本文件,附加一些html标记,然后将其保存到java中用户选择的目录中,java,html,file-io,tags,text-files,Java,Html,File Io,Tags,Text Files,我希望输入和输出目录都由用户选择 以下是我迄今为止尝试过的代码: public class FileOpen<FileChooser> extends JPanel implements ActionListener { private static final long serialVersionUID = 1L; static private final String newline = "\n"; JButton openButton, co

我希望输入和输出目录都由用户选择

以下是我迄今为止尝试过的代码:

public class FileOpen<FileChooser> extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;
         static private final String newline = "\n";
     JButton openButton, convertButton;
     JTextArea log;
        JFileChooser fc;

    public FileOpen() {
        super(new BorderLayout());

        log = new JTextArea(5, 20);
        log.setMargin(new Insets(5, 5, 5, 5));
        log.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(log);

        // Create a file chooser
        fc = new JFileChooser();

        openButton = new JButton("Open a Text File...");

        openButton.addActionListener(this);

        convertButton = new JButton("Convert to HTML File...");

        convertButton.addActionListener(this);

        // For layout purposes, put the buttons in a separate panel
        JPanel buttonPanel = new JPanel(); // use FlowLayout
        buttonPanel.add(openButton);
        buttonPanel.add(convertButton);

        // Add the buttons and the log to this panel.
        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e) {

        // Handle open button action.
        if (e.getSource().equals(openButton)) {
            fc.setMultiSelectionEnabled(true);
            FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    "Only Text Files", "txt");
            fc.setFileFilter(filter);

            int returnVal = fc.showOpenDialog(FileOpen.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File files[] = null;

                files = fc.getSelectedFiles();

                for (int i = 0; i <= files.length - 1; i++) {
                    log.append("Opening " + files[i].getName() + "\n ");

                    try {

                        FileReader fr = new FileReader(files[i]);
                        BufferedReader br = new BufferedReader(fr);
                        String strLine;
                        StringBuilder fileContent = new StringBuilder();
                        // Read File Line By Line
                        log.append("Reading files " + files[i].getName()
                                + "\n ");
                        while ((strLine = br.readLine()) != null) {

                            String tokens[] = strLine.split(" ");
                            if (tokens.length > 0) {
                                fileContent.append(strLine);
                                fileContent.append("<br />");
                                FileWriter fstreamWrite = new FileWriter(
                                        files[i]);
                                fstreamWrite.write("<START>");
                                fstreamWrite.write("\n");
                                fstreamWrite.write("<TITLE> </TITLE>");
                                fstreamWrite.write("\n");
                                fstreamWrite.write("<BODY>");
                                fstreamWrite.write("\n");
                                BufferedWriter out = new BufferedWriter(
                                        fstreamWrite);
                                RandomAccessFile raf = new RandomAccessFile(
                                        files[i], "rw");
                                raf.seek(0);
                                out.write(fileContent.toString());
                                out.newLine();
                                out.write("</BODY>");
                                out.newLine();
                                out.write("<END>");
                                out.newLine();
                                System.out.println(fileContent);
                                raf.close();
                                out.flush();
                                out.close();
                                br.close();

                            }

                        }

                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                }
            } else {
                log.append("Operation Canceled \n");
            }

            // Handle Covert button action.
        } else if (e.getSource() == convertButton) {

        }

    }

    @SuppressWarnings("rawtypes")
    private static void createAndShowGUI() {
        // Create and set up the window.
        JFrame frame = new JFrame("TextToHtml");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Add content to the window.
        frame.add(new FileOpen());

        // Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Turn off metal's use of bold fonts
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
}
公共类FileOpen扩展JPanel实现ActionListener{
私有静态最终长serialVersionUID=1L;
静态私有最终字符串换行符=“\n”;
JButton openButton,convertButton;
jtext面积测井;
JFileChooser fc;
公共文件打开(){
超级(新边框布局());
log=新的JTextArea(5,20);
log.setMargin(新插图(5,5,5,5));
log.setEditable(false);
JScrollPane logScrollPane=新的JScrollPane(日志);
//创建一个文件选择器
fc=新的JFileChooser();
openButton=newjbutton(“打开文本文件…”);
openButton.addActionListener(这个);
convertButton=newjbutton(“转换为HTML文件…”);
convertButton.addActionListener(此);
//为了便于布局,请将按钮放在单独的面板中
JPanel buttonPanel=new JPanel();//使用FlowLayout
按钮面板。添加(打开按钮);
按钮面板。添加(转换按钮);
//将按钮和日志添加到此面板。
添加(按钮面板,边框布局。页面\开始);
添加(logScrollPane,BorderLayout.CENTER);
}
已执行的公共无效操作(操作事件e){
//处理打开按钮动作。
if(例如getSource().equals(openButton)){
fc.setMultiSelectionEnabled(真);
FileNameExtensionFilter=新FileNameExtensionFilter(
“仅限文本文件”、“txt”);
fc.设置文件过滤器(过滤器);
int returnVal=fc.showOpenDialog(FileOpen.this);
if(returnVal==JFileChooser.APPROVE_选项){
文件[]=null;
files=fc.getSelectedFiles();
对于(int i=0;i 0){
追加(strLine);
fileContent.append(“
”); FileWriter fstreamWrite=新的FileWriter( 档案[i]; fstreamWrite.write(“”); fstreamWrite.write(“\n”); fstreamWrite.write(“”); fstreamWrite.write(“\n”); fstreamWrite.write(“”); fstreamWrite.write(“\n”); BufferedWriter out=新的BufferedWriter( fstreamWrite); RandomAccessFile raf=新的RandomAccessFile( 文件[i],“rw”); raf.seek(0); out.write(fileContent.toString()); out.newLine(); 请写出(“”); out.newLine(); 请写出(“”); out.newLine(); System.out.println(文件内容); raf.close(); out.flush(); out.close(); br.close(); } } }捕获(IOE1异常){ //TODO自动生成的捕捉块 e1.printStackTrace(); } } }否则{ log.append(“操作已取消\n”); } //处理隐藏按钮操作。 }else if(例如getSource()==convertButton){ } } @抑制警告(“原始类型”) 私有静态void createAndShowGUI(){ //创建并设置窗口。 JFrame=newjframe(“TextToHtml”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //向窗口添加内容。 frame.add(新文件打开()); //显示窗口。 frame.pack(); frame.setVisible(true); } 公共静态void main(字符串[]args){ SwingUtilities.invokeLater(新的Runnable(){ 公开募捐{ //关闭metal对粗体字体的使用 UIManager.put(“swing.boldMetal”,Boolean.FALSE); createAndShowGUI(); } }); } }
下面的代码适用于单个文件,必须为源文件和目标文件指定路径,但我希望它是用户选择的目录,如 1. /目录-> abc.txt adc.txt, 选择此目录进行操作,进行更改,然后在保存时再次选择目标目录,以使用.html扩展名保存这些文件

public class TextToHtml {
public static void main(String args[]) {
    try {
        // Open the file that is the first

        String sourcepath = "C:/Documents and Settings/Administrator/Desktop/Test/UAE0b143800.txt";

        FileInputStream fstream = new FileInputStream(sourcepath);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                fstream));
        String strLine;
        StringBuilder fileContent = new StringBuilder();
        // Read File Line By Line

        while ((strLine = br.readLine()) != null) {

            String tokens[] = strLine.split(" ");
            if (tokens.length > 0) {
                {
                    fileContent.append(strLine);
                    fileContent.append("<br />");
                }
            }
        }
        // Now fileContent will have updated content , which you can
        // override into file

        String targetpath = "C:/Documents and Settings/Administrator/Desktop/Target/UAE0b143800.html";

        // To trim file Extension
        String title = targetpath;
        title = title.substring(0, title.lastIndexOf('.'));
        br.close();

        FileWriter fstreamWrite = new FileWriter(targetpath);
        fstreamWrite.write("<START>");
        fstreamWrite.write("\n");
        fstreamWrite.write("<TITLE>" + title + "</TITLE>");
        fstreamWrite.write("\n");
        fstreamWrite.write("<BODY>");
        fstreamWrite.write("\n");

        BufferedWriter out = new BufferedWriter(fstreamWrite);

        RandomAccessFile raf = new RandomAccessFile(targetpath, "rw");
        raf.seek(0);

        out.write(fileContent.toString());
        out.newLine();
        out.write("</BODY>");
        out.newLine();
        out.write("<END>");
        out.newLine();
        out.close();
        raf.close();
        // in.close();
    } catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}
公共类TextToHtml{
公共静态void main(字符串参数[]){
试一试{
//打开第一个文件
String sourcepath=“C:/Documents and Settings/Administrator/Desktop/Test/UAE0b143800.txt”;
FileInputStream fstream=新的FileInputStream(sourcepath);
BufferedReader br=新的BufferedReader(新的InputStreamReader(
),;
弦斯特林;
StringBuilder fileContent=新的StringBuilder();
//逐行读取文件
而((strLine=br.readLine())!=null){
字符串标记[]=strLine.split(“”);
如果(tokens.length>0){
{
追加(strLine);
fileContent.append(“
”); } } } //现在fileContent将有更新的内容,您可以 //覆盖到文件中 String targetpath=“C:/Documents and Settings/Administrator/Desktop/Target/UAE0b143800.html”; //修剪文件扩展名 字符串标题=targetpath; title=tit