java如图:点击浏览按钮把文本框的内容保存到指定文件夹,完整的代码该怎么写啊,谢各位大神
复制我之前的答案。
其实在浏览器里面是不行的。因为浏览器为了安全并没有给前端访问本地资源的权限,但是可以通过浏览器 API 下载的方式来将内容保存成本地 TXT 文件。
不过像这种不同浏览器有不同 API 的东西,自己太麻烦了,我曾经用过 FileSaver.js 这个库来下载过在金山词霸上的错词表,自己读取表单内容在 js 里拼装成你想要的样子然后调用库就行了,很方便。
官方实例:
12var file = new File(["Hello, world!"], "hello world.txt", {type: "text/plain;charset=utf-8"});saveAs(file);上面示例会保存 “Hello, world!” 到 hello world.txt 文件,你想要 a.htm 就把第二个参数改成 a.htm 就成。
参考下面代码:
123456789101112131415161718192021222324252627282930313233343536373839404142434445import java.io.*;import javax.swing.*;import java.awt.FlowLayout;import java.awt.event.*;public class WriterTo extends JFrame implements ActionListener{ JButton b;JTextField t; public WriterTo(){ super("文本框内容写入文件"); JLabel l=new JLabel("请输入内容:"); t=new JTextField(20); b=new JButton("写入"); b.addActionListener(this); this.add(l); this.add(t); this.add(b); this.setLayout(new FlowLayout()); this.pack(); this.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b){ if(t.getText().equals("")){ JOptionPane.showMessageDialog(null,"请输入内容~","错误",JOptionPane.ERROR_MESSAGE); t.grabFocus(); }else{ write(t.getText()); JOptionPane.showMessageDialog(null,"写入成功","提示",JOptionPane.INFORMATION_MESSAGE); } } } public void write(String line){ try{ File f=new File("c:/文本框.txt");//向指定文本框内写入 FileWriter fw=new FileWriter(f); fw.write(line); fw.close(); }catch(Exception e){ } } public static void main(String[] args) { new WriterTo(); } }很简单的,给浏览加一个点击时间,然后只要触发了,就将文本框中的保存起来,就行了
热门标签: