从零双排java之输入输出流

 * 流 (以字节为单位 进行数据的传输)

 * 以参照物(你的程序)来衡量 是输出  还是输入

 * 字节输出流  程序-->文件

 * OutPutStream

 * 字节输入流  文件--程序

 * InPutStreanm

 * 以上两个抽象类是所有字节流的父类

FileWriter  字符输出流

FilieReader  字符输入流

上面两个类是  所有字符流的父类(抽象类)

在io流中出现的异常都是IoException异常

// 创建文件字节输出流
		File file = new File("/Users/lanou/Desktop/Test/jsy.txt");
		// 给出的路径可以没有该文件,没有这个文件系统会帮你创建这个文件
		FileOutputStream fos = new FileOutputStream(file);
		// 写文件时 出现的异常都是Io异常
		// 传入int值得方法 是按ASCII码输入 一次写入一个字节
		fos.write(58);
		// 创建一个字节数组
		byte[] b = { 66, 34, 78, 12 };
		fos.write(b, 1, 2);
		// 直接写字符串
		// 字符串转字节数组 getByTes();
		fos.write("wanglong".getBytes());
		// 关闭资源
		fos.close();

如何对文件在不删除原有内容的情况下进行续写:在输出流的参数中,第二个参数填true

FileOutputStream fos = new FileOutputStream(file,true);

读取文件:

read();可以读取文件中的内容 并且返回读取到的字节数或者字符数   没读到字符就会返回-1

常用while循环 读取一个文件中的内容

// 循环
		int num = 0;
		while ((num = fis.read()) != -1) {
			System.out.println((char) num);

复制文件并修改文件后缀

public class Demo03 {
	public static void main(String[] args) throws IOException {
		// 将一个文件夹下的所有txt文件 复制 到另一个文件夹下并且保存为.java文件
		File src = new File("/Users/lanou/Desktop/Test");
		File dest = new File("/Users/lanou/Desktop/copy");
		copyTxtTOJava(src, dest);
	}


	public static void copyTxtTOJava(File src, File dest) throws IOException {
		File[] files = src.listFiles(new Gl());
		for (File subFile : files) {
			if (subFile.isFile()) {
				//读写
				int len = -1;
				byte[] bts = new byte[1024];
				FileInputStream fis = new FileInputStream(subFile);
				//构建写的路径
				String replaceFirst = subFile.getName().replaceFirst("txt", "java");
				File tempfile = new File(dest, replaceFirst);
				FileOutputStream fos = new FileOutputStream(tempfile);
				//写入目标文件		
				while ((len = fis.read(bts)) != -1) {
					fos.write(bts, 0, len);
				}

			} else {
				copyTxtTOJava(subFile, dest);
			}
		}
	}
}

class Gl implements FileFilter {
	@Override
	public boolean accept(File pathname) {
		if (pathname.isDirectory()) {
			return true;
		}
		if (pathname.getName().endsWith(".txt")) {
			return true;
		}
		return false;
	}
}



猜你喜欢

转载自blog.csdn.net/jsyMax/article/details/80500677