作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写一个小应用程序,想为两个按钮添加相同的处理程序:“保存”和“另存为”。对于保存,如果文件存在,则不应打开 JFileChooser,只需保存内容,但使用我当前的代码,它总是打开对话框。我该怎么做呢?这是我的代码
public void actionPerformed(ActionEvent e) {
JComponent source = (JComponent)e.getSource();
if (pathToFile.length()>0){
File file = new File(pathToFile);
if (file.exists()){
try(FileWriter fw = new FileWriter(file.getName() + ".txt", true)){
fw.write(area.getText());
}
catch(Exception ex){
System.out.println(ex.toString());
}
}
}
else{
if (fchoser.showSaveDialog(source.getParent())== JFileChooser.APPROVE_OPTION){
try(FileWriter fw = new FileWriter(fchoser.getSelectedFile()+".txt")){
fw.write(area.getText());
f.setTitle(fchoser.getSelectedFile().getPath());
pathToFile = fchoser.getSelectedFile().getPath();
}
catch(Exception ex){
}
}
}
更新添加了代码来检查文件是否存在。确实如此,也不异常(exception),但附加文本不写。
最佳答案
与您的问题无关,但是:
fw.write(area.getText());
不要使用 FileWriter 的 write 方法。这将始终使用“\n”作为行分隔符将文本写入文件,这对于您的代码运行的操作系统可能正确,也可能不正确。
您可以使用 JTextArea
的 write(...)
方法:
area.write(fw);
然后将使用正确的行分隔符。
关于Java swing 使用 JFileChooser 进行保存和另存为功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37631476/
我有 json 数据: { "products": [ { "productId" : 0, "productImg" : "../img/product-ph
我是一名优秀的程序员,十分优秀!