InputStream/OutputStream---读写文件

文件

在这里插入图片描述

读文件


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ThreadTest {
	public static void main(String[] args) {
		File file = new File("D:\\新建文件夹\\test.txt");
		// 读文件
		FileInputStream fin = null;
		byte[] words = new byte[3];// UTF-8下,中文占3个字节,一次读一个字符,防止乱码,可以换为其他的,只要是3的倍数,就不会出现乱码
		try {
			fin = new FileInputStream(file);
			System.out.println("开始读文件:");
			int n = fin.read(words);// 第一次读,返回读到的字节数
			while (n != -1) {// 读到末尾为-1
				System.out.println("此次读了" + n + "个字节,内容为:" + new String(words, 0, n));
				n = fin.read(words);// 继续读
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fin != null) {// 关闭文件输入字节流
				try {
					System.out.println("关闭读文件!");
					fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

在这里插入图片描述

写文件


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ThreadTest {
	public static void main(String[] args) {
		File file = new File("D:\\新建文件夹\\test.txt");
		// 写文件
		FileOutputStream fs = null;
		try {
			fs = new FileOutputStream(file, true);// true:追加方式
			String sayword = "天行健,君子以自强不息!";
			System.out.println("开始写文件,其内容为:" + sayword);
			fs.write(sayword.getBytes());// 写字节数组
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fs != null) {// 关闭文件输出字节流
				try {
					System.out.println("关闭写文件!");
					fs.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值