0

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

以下是我到目前为止尝试过的代码:

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();
            }
        });
    }
}
4

1 回答 1

1

下面的代码适用于单个文件,并且必须为源和目标指定路径,但我希望它是用户选择性目录,如 1. /Dir-> 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());
    }
}

}

于 2013-10-11T05:13:35.713 回答