您好我正在为大学的模块编写java文本编辑器。我在将字体样式和大小保存到富文本文件时遇到一些麻烦我目前正在使用printwriter方法将文本区域中的文本写入文件。我在下面包含了我的saveFile代码。这是我的第一次发帖,如果我的帖子有任何问题,我很抱歉,提前谢谢。
public class saveFile implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e){
//allow user to enter file name
String s = JOptionPane.showInputDialog("Input name of file:");
String w = "";
try
{
//Allow user to enter directory
w = JOptionPane.showInputDialog("Input Directory where you want the file:\n"
+ "eg C:\\ for C drive");
}
catch(Exception writeFile)
{
JOptionPane.showMessageDialog(null, "Task could not be completed\nPlease try again"
,"File Write Error", JOptionPane.ERROR_MESSAGE, null);
}
//try catch block
try
{
//check if fields are null or empty
if(!(s.isEmpty() && w.isEmpty()) && (w != null && s != null))
{
try
{
//Create new file and append with .rtf
File userFile = new File(w + s + ".rtf");
PrintWriter file = new PrintWriter(userFile);
//set files content = text
file.print(text.getText());
file.close();
File dir = new File(w);
if(dir.exists())
{
JOptionPane.showMessageDialog(null, "File " + s + " created\n" + "Saved in " + w, null,JOptionPane.PLAIN_MESSAGE );
}
else
{
throw new Exception();
}
}
catch(Exception fileNotCreatedException)
{
JOptionPane.showMessageDialog(null,"File not created\n"
+ "Please check to see directory exists","File Error",
JOptionPane.ERROR_MESSAGE, null);
fileNotCreatedException.printStackTrace();
}
}
}
答案 0 :(得分:0)
如果您使用内容类型text/rtf
使用JTextPane进行摇摆,则RTFEditorKit将用于StyledDocument。
OutputStream out = new FileOutputStream(userFile);
StyledDocument doc = textPane.getStyledDocument();
StyledEditorKit editorKit = textPane.getStyledEditorKit();
editorKit.write(out, doc, 0, doc.getLength());
由于HTMLEditorKit也是基于StyledDocument的,因此有时可能需要先付费使用HTML,因为HTML语法更容易。