java实现日记软件_建立日记类

建立日记类

一、实验说明

本节目标

这本节中,我们将完成日记类。实现将用户的记录的日记写入到本地磁盘中。

二、具体实现

建立 Diary.java,不多说,直接上代码

package com.Joke.util;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import javax.swing.text.Document;

public class Diary {

public static void addDiary(String pathname, String title, String txt) {

// pathname是以用户名命名的文件夹

File dirfile = new File(pathname);

BufferedWriter bufw = null;

// 建立文件夹

dirfile.mkdirs();

// 建立日记文件,后缀为.kz

File file = new File(dirfile, title + ".ky");

try {

//写入文件

bufw = new BufferedWriter(new FileWriter(file, true));

bufw.write(txt);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

if (bufw != null) {

try {

bufw.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

public static void read(File file, Document doc) {

// 创建读取流,读取文件内容,并将读到的内容添加到日记显示区

try (BufferedReader bufr = new BufferedReader(new FileReader(file));) {

String txt = null;

// 获取换行符,因为Linux和Windows下的换行符是不一样的。这样可以增强跨平台性

String line = System.getProperty("line.separator");

while ((txt = bufr.readLine()) != null) {

doc.insertString(doc.getLength(), txt + line, null);

}

} catch (Exception e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值