📄 manage.java
字号:
package a.b.c;import java.io.FileInputStream;import java.io.FileOutputStream;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;public class Manage{ /** * 存储留言到文件 * @param content * @throws Exception */ public static synchronized void save(String content) throws Exception { try { //文件输出流FileOutputStream第二个参数为 true,是将字节写入文件末尾处,而不是写入文件开始处。 FileOutputStream outs = new FileOutputStream("notebook.txt", true); //写入留言分割表示线 outs.write("----------+----------+----------\r\n".getBytes("GBK")); //写入留言时间 Date nowTime = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); String s = sdf.format(nowTime); outs.write((s + "\r\n").getBytes("GBK")); //写入留言内容 outs.write(content.getBytes("GBK")); outs.write("\r\n".getBytes("GBK")); //关闭流 outs.close(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * 获取留言列表 * @return * @throws Exception */ public static synchronized ArrayList<Content> list() throws Exception { //返回集合 ArrayList<Content> retList = new ArrayList<Content>(); try { //创建文件输入流 FileInputStream ins = new FileInputStream("notebook.txt"); //读文件内容字节数组 byte[] content = new byte[64 * 1024]; //读文件 ins.read(content, 0, content.length); //关闭文件流 ins.close(); //转为java字符串 String notes = new String(content, "GBK").trim(); //System.out.println("文件:"); //System.out.println(notes); //在留言notes中的偏移地址 int index = 0; while ((index = notes.indexOf("----------+----------+----------\r\n", index)) != -1) { //一个留言对象 Content obj = new Content(); //加入集合 retList.add(obj); //时间起始地址 int time_start = index + "----------+----------+----------\r\n".length(); //时间终止地址 int time_end = notes.indexOf("\r\n", time_start) + "\r\n".length(); //时间字符串 String time = notes.substring(time_start, time_end).trim(); //System.out.println("时间:"); //System.out.println(time); obj.setSaveTime(time); //内容起始地址 int note_start = time_end; //内容终止地址 int note_end = notes.indexOf("----------+----------+----------\r\n", note_start); //内容字符串 String note; if (note_end == -1) { note = notes.substring(note_start).trim(); index = note_start; } else { note = notes.substring(note_start, note_end).trim(); index = note_end; } obj.setContent(note); } } catch (Exception e) { e.printStackTrace(); throw e; } return retList; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -