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();
				}
			}
		}
	}
}

在这里插入图片描述

发布了32 篇原创文章 · 获赞 1 · 访问量 2820

猜你喜欢

转载自blog.csdn.net/YOUAREHANDSOME/article/details/105451260