日期:2014-05-20 浏览次数:21144 次
import java.io.*;
import javax.swing.*;
public class TestNotepad {
public static void main(String[] args) throws IOException {
stringToFile("Hello\nWorld");
stringToFile("Hello\r\nWorld");
;
}
public static void stringToFile(String sourceString) {
PrintWriter pw = null;
try {
JFileChooser jFileChooser = new JFileChooser();
javax.swing.filechooser.FileFilter fileFilter = new javax.swing.filechooser.FileFilter() {
public boolean accept(File file) {
if (file.isDirectory())
return true;
String fileName = file.getName();
if (fileName.toUpperCase().endsWith("TXT"))
return true;
return false;
}
public String getDescription() {
return "保存为文本文件";
}
};// 建立一个过滤文件类型的过滤器(对话框中正确显示文件),是否启用过滤器决定于下面两句话
// jFileChooser.addChoosableFileFilter(fileFilter);
// jFileChooser.setFileFilter(fileFilter);
int returnValue = jFileChooser.showSaveDialog(null);
File fileOfSave = null;// 保存文件句柄
if (returnValue == javax.swing.JFileChooser.APPROVE_OPTION) {
fileOfSave = jFileChooser.getSelectedFile();// 获得文件句柄,文件是否存在还未知
}
if(fileOfSave == null) return;
String fileNameOfSave = fileOfSave.getName();// 返回输入的文件名
// 检查文件名是否符合要求,这一步暂时省略......................................
if (fileOfSave.exists() && !isAgree("该文件已经存在,确定要覆盖吗?"))
return;
else
fileOfSave.createNewFile();
pw = new PrintWriter(fileOfSave);
pw.print(sourceString);
pw.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (pw != null)
pw.close();
}
}
public static boolean isAgree(String hint) {
int returnValue = javax.swing.JOptionPane.showConfirmDialog(null, hint);
if (returnValue == javax.swing.JOptionPane.YES_OPTION)
return true;
else
return false;
}
public static int prompt(String promptMessage) {
return JOptionPane.showConfirmDialog(null, promptMessage, "友情提示",
JOptionPane.WARNING_MESSAGE);
}
} /* (Execute to see output) */// :~
------解决方案--------------------
如果有跨平台使用的要求,可以使用 String str= System.getProperty("line.separator"); 来获取换行符。 linux使用 \n windows使用\r\n 其它操作系统可能也不同。
------解决方案--------------------
用System.getProperty("line.separator")