我使用FileWriter制作了一个Note程序。它工作得很好,除非我写了一个长音符,音符只会保存在一行中。 我有什么方法可以让它在一定数量的字符后写入下一行吗? 这是我的代码:
import static javax.swing.JOptionPane.*;
import static java.lang.Integer.*;
import static java.lang.System.*;
import static java.lang.Double.*;
import static java.lang.Math.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.text.*;
import java.awt.*;
import java.io.*;
public class Note extends JFrame implements ActionListener {
JTextArea area;
JTextField title;
JLabel titleTxt, noteTxt;
JButton save, clear, exit;
FileWriter writer=null;
PrintWriter gen =null;
Scanner reader =null;
boolean append = true;
public static void main(String[] args) {
Note window = new Note();
window.setTitle("Note");
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.createGUI();
window.setSize(300,250);
window.setResizable(false);
window.setVisible(true);
}
public void createGUI() {
setLayout ( new FlowLayout() );
titleTxt = new JLabel("Title:");
add(titleTxt);
title = new JTextField(30);
add(title);
noteTxt = new JLabel("Note:");
add(noteTxt);
area = new JTextArea(5,25);
area.setLineWrap(true);
area.setWrapStyleWord(true);
JScrollPane field = new JScrollPane(area);
add(field);
save = new JButton("Save");
save.addActionListener(this);
add(save);
clear = new JButton("Clear");
clear.addActionListener(this);
add(clear);
exit = new JButton("Exit");
exit.addActionListener(this);
add(exit);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == save){
Save();
area.setText("");
title.setText("");
}
else if(e.getSource() == clear){
area.setText("");
title.setText("");
}
else if(e.getSource() == exit){
System.exit(0);
}
}
private void Save(){
String date = new SimpleDateFormat("dd-MM-yyyy").format(Calendar.getInstance().getTime());
String timeStamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
String outTxt = "Note is saved";
try{
//FileWriting
File file = new File(date+".txt");
writer = new FileWriter(file,append);
writer.write("Tid: "+timeStamp+"\r\n");
writer.write("\r\n");
writer.write(title.getText()+"\r\n");
writer.write("\r\n");
writer.write(area.getText()+"\r\n");
writer.write("\r\n");
writer.write("\r\n");
writer.close();
}
catch (FileNotFoundException e){
outTxt="File Not Found";
}
catch (Exception e){
outTxt="Error";
}
finally {
if (reader!=null)reader.close();
showMessageDialog(null, outTxt);
}
}
}
答案 0 :(得分:0)
最简单的方法是做这样的事情:
try{
//FileWriting
File file = new File(date+".txt");
writer = new FileWriter(file,append);
writer.write("Tid: "+timeStamp+"\r\n");
writer.write("\r\n");
writer.write(title.getText().replaceAll("(.{50}[^ ]+)\\s+", "$1\r\n")+"\r\n");
writer.write("\r\n");
writer.write(area.getText().replaceAll("(.{50}[^ ]+)\\s+", "$1\r\n")+"\r\n");
writer.write("\r\n");
writer.write("\r\n");
writer.close();
}
这将替换50个字符和任何后续非空格字符,并将它们放在一个组中,并将它们替换为同一组和\r\n
。