本人是新手,在学习java如何打开文件和保存文件,功能很简单,实现起来也不麻烦。
附源代码:
public class FileOpenAndSave extends JFrame{ private static final long serialVersionUID = 4029562126308556571L; private JPanel panel1, panel2; private TextArea ta; private JButton open, save; private JLabel label; public FileOpenAndSave() { setSize(400, 300); setTitle("FileOpenDemo"); setLocation(400, 400); panel1 = new JPanel(new BorderLayout()); panel1.setPreferredSize(new Dimension(280, 280)); ta = new TextArea(); panel1.add(ta, BorderLayout.CENTER); open = new JButton("Open File");// 打开文件按钮 save = new JButton("Save File");// 保存文件按钮 // 为打开文件按钮注册监听器 open.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser("请选择文件"); FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件(*.txt)", "txt"); chooser.setFileFilter(filter); int res = chooser.showOpenDialog(null); if(res == JFileChooser.APPROVE_OPTION){ File file = chooser.getSelectedFile(); String path = file.getAbsolutePath(); try { // 注意编码问题 InputStreamReader reader = new InputStreamReader(new FileInputStream(path), "utf-8"); char[] buf = new char[1024]; int len = 0; CharBuffer cb = CharBuffer.allocate((int) file.length()); while((len = reader.read(buf)) > -1){ cb.put(buf, 0, len); } reader.close(); String str = new String(cb.array()); // 此段代码功能是将所读文件复制到相同路径下 /*int sep = path.lastIndexOf("\\"); path = path.substring(0, sep + 1) + "copy.txt"; OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(path)); writer.write(cb.array()); writer.close();*/ ta.setEditable(false); ta.setText(str); } catch (Exception e1) { e1.printStackTrace(); } } } }); // 为保存文件按钮注册监听器 save.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String path; String content = ta.getText(); JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件(*.txt)", "txt"); chooser.setFileFilter(filter); int res =chooser.showSaveDialog(null); if(res == JFileChooser.APPROVE_OPTION){ path = chooser.getSelectedFile().getAbsolutePath() + ".txt";// 获得保存路径 try { // 注意编码问题 OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(path), "gbk"); writer.write(content); writer.close(); } catch (IOException e1) { e1.printStackTrace(); } } } }); label = new JLabel("hhshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"); label.setVisible(false); panel2 = new JPanel(new FlowLayout()); panel2.add(label); panel2.add(open); panel2.add(save); add(panel1, BorderLayout.CENTER); add(panel2, BorderLayout.SOUTH); setResizable(false); enableInputMethods(false); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new FileOpenAndSave(); } }