java的io体系

输入流

java 的io按数据类型分为字节流和字符流,按功能类型分为输入流和输出流,按功能体系分为低级流和处理流。
输入流:InputStream 和 Reader
InputStream的方法有:
int read():读取单个字节,返回读取的字节数
read(byte[] b):读取长度为b.length的字节数组,存储在数组中,返回读取到的字节数
read(byte[] b,int off,int len):从off开始读取len字节,存储在b数组中,返回实际读取的字节数
实例:

public class FileInputStreamTest {
	public static void main(String[] args) {
		int hasRead = 0;
		byte[] b = new byte[1024];
		FileInputStream fs;
		try {
			fs = new FileInputStream("C:\\Users\\szl\\Desktop\\新建文本文档.txt");
			while((hasRead = fs.read(b)) > 0){
				System.out.println(new String(b,0,hasRead));
			}
			fs.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
}

Reader的方法:
int read():读取单个字符,返回读取的字符数
int read(char[] cbuf):读取数组长度的字符,存储到数组中,返回读取到的字符数
int read(char[] cbuf,int off,int len):从指定位置,读取指定长度的字符,存储在数组中,并返回读取的字符数。
实例:

public class FileReaderTest {
	public static void main(String[] args) {
		int hasRead = 0;
		char[] cbuf = new char[32];
		try {
			Reader reader = new FileReader("C:\\Users\\szl\\Desktop\\新建文本文档.txt");
			while((hasRead = reader.read(cbuf)) > 0){
				System.out.println(new String(cbuf,0,hasRead));
			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

注意到:

  • InputStream/OutputStream,Reader/Writer都是抽象基类,此外转换流(将字节流转换为字符流,包含InputStreamReader和OutputStreamWriter两类)是抽象基类,不能实例化。

输出流

OutputStream和Writer:
OutputStream包含的方法有:
void write():将指定的字节写入到输出流中
void write(byte[] b):将字节数组写入到输入流中
void write(byte[] b,int off,int len):从指定位置将字节数组的len长度写入到输入流中
Writer的方法相同,不赘述。
实例:

/*
* 从输入流中读取数据,写道输出流中,相当于复制文件
*/
public class FileOutputStreamTest {
	public static void main(String[] args) {
		int hasRead = 0;
		byte[] b = new byte[1024];
		try {
			FileInputStream fs = new FileInputStream("C:\\Users\\szl\\Desktop\\新建文本文档.txt");
			FileOutputStream fos = new FileOutputStream("C:\\Users\\szl\\Desktop\\新建文本文档_1.txt");
			while((hasRead = fs.read(b)) > 0){
				fos.write(b,0,hasRead);
			}
			fs.close();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

低级流的功能有限,常常使用处理流将其包裹起来,以实现如缓冲区功能等更强大的功能。(以PrintStream为例)只需要将低级流作为参数即可,如

FileInputStream fs = new FileInputStream("C:\\Users\\szl\\Desktop\\新建文本文档.txt");
PrintStream ps = new PrintStream(fs);

高级流(转换流)

使用高级流的好处:

 A <code>PrintStream</code> adds functionality to another output stream,
 * namely the ability to print rep resentations of various data values
 * conveniently.  Two other features are provided as well.  Unlike other output
 * streams, a <code>PrintStream</code> never throws an
 * <code>IOException</code>; instead, exceptional situations merely set an
 * internal flag that can be tested via the <code>checkError</code> method.
 * Optionally, a <code>PrintStream</code> can be created so as to flush
 * automatically; this means that the <code>flush</code> method is
 * automatically invoked after a byte array is written, one of the
 * <code>println</code> methods is invoked, or a newline character or byte
 * (<code>'\n'</code>) is written.
 *
 * <p> All characters printed by a <code>PrintStream</code> are converted into
 * bytes using the platform's default character encoding.  The <code>{@link
 * PrintWriter}</code> class should be used in situations that require writing
 * characters rather than bytes.
一:不会报IOException
二:自动对齐(换行回车)

重定向输入/输出流

我们知道java的标准输入输出是通过System类实现的,其中System.in和System.out分别代表键盘和显示器,如果需要更改默认输入输出,System提供了三个方法:

  1. system.setIn(InputStream in)
  2. System.setOut(PrintStream os)
  3. System.setErr(PrintStream err)
    在这里,主要到,setOut的参数不是OutputStream而是PrintStream

实例:

/*
 * 重定向标准输入到文件
 */
public class NewInTest {
	public static void main(String[] args) {
		FileInputStream in;
		try {
			in = new FileInputStream("C:\\Users\\szl\\Desktop\\new_1.txt");
			System.setIn(in);
			Scanner sc = new Scanner(System.in);
			while(sc.hasNext()) {
				String content = sc.nextLine();
				System.out.println(content);
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}

/*
 * 重定向标准输出到文件
 */
public class NewOutTest {
	public static void main(String[] args) {
		FileOutputStream fos;
		try {
			fos = new FileOutputStream("C:\\Users\\szl\\Desktop\\new_2.txt");
			PrintStream out = new PrintStream(fos);
			System.setOut(out);
			
			System.out.println("hello world");
			System.out.println("hello world");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

文档/目录操作

  • 目录的增删改查
  • 迭代遍历本地所有目录

java提供一个java.io.File类操作文件,File类对象可以是一个文件路径字符串,也可以是一个文件对象,但是不能操作文件内容,要想操作文件内容,必须使用流的方式。

  abstract, system-independent view of hierarchical pathnames.分层路径名视图
 
  File file = new File("C:/Users/sss/Desktop/example.txt");

创建文件
-- boolean createNewFile()  
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
只有当这个路径名不存在的时候才能创建,及路径中不能存在于文件同名的子目录

static File createTempFile(String prefix,String suffix)
Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
创建空文件在默认临时文件目录,使用指定的前缀和后缀

static File createTempFile(String prefix,String suffix,File directory)
根据指定的前缀后缀,加上随机数作文件名,在指定的路径生成文件
目录查看
File getAbsoluteFile()       Returns the absolute form of this abstract pathname
String getAbsoulutePath()     获取路径的字符串表示

String getParent()   返回去掉这个路径最后一截的路径
File getParentFile()  返回File对象

String getName()    返回表示这个虚拟路径的文件或目录的名称(文件的名称,路径的最后一段)

String getPath()         返回对象的路径字符串,把路径对象转化为路径字符串

File[] listFiles() 返回虚拟路径的目录列表,如果file对项不是目录,报NullPointerException错
File[] listRoots() 返回系统的根路径
删除文件
boolean delete()           
工具类型方法
boolean exists()
boolean isDictionary()
boolean isFile()
boolean renameTo(File dest)  重命名
创建目录
boolean mkdir()  创建目录
boolean mkdirs()  创建目录,会创建不存在的parentPath

应用:

String 使用"."分割的时候,需要转义。写成“\\.”的形式

	public static void method3() {
		// 获取所有word、txt格式的文件名
		File f1 = new File("C:/Users/szl/Desktop");
		// 获取桌面所有文件的文件名
		File[] list = f1.listFiles();
		for(File f:list) {
		// 获取每一个文件名,对比后缀
			String filename = f.getName();	
		//	文件名中必须包含后缀
			if(filename.contains(".")) {
				String suffix = filename.split("\\.")[1];
			if(!f.isDirectory() && suffix !=null && (suffix.equals("docx")|| suffix.equals("txt") || suffix.equals("doc"))) {
				System.out.println(f.getName());
			}
				}
		}
	}

  • 遍历目录
package foo.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class FileTest {
	public static void writeToFile(String str) throws IOException {
		// 把信息写入文件,FileOutputStream构造器中的boolean append,改变为增加模式
		FileOutputStream out = new FileOutputStream("C:/Users/szl/Desktop/record.txt",true);
		// 转换成字符流
		OutputStreamWriter writer = new OutputStreamWriter(out);
		// 写入文件
		writer.write(str + "\r\n");
		writer.close();
	}
	
	public static void createFile() throws IOException{
		// 创建文件,用来存储数据
		File newfile = new File("C:/Users/szl/Desktop/record.txt");
		newfile.createNewFile();
	}
	
	public static void traversalAllDir(File file) throws NullPointerException,IOException {
		// 遍历磁盘所有文件目录
		if(file.isDirectory()) { 
			File[] list = file.listFiles();
			for(File f:list) {
				if(f.isFile()) {
					String str = f.getAbsolutePath();
					System.out.println(str);
					writeToFile(str);
				}else {
					traversalAllDir(f);
				}
			}
		}
	}
	
	public static void main(String[] args) throws IOException {
		createFile();
		File start = new File("E:\\java\\javaee\\eclipse");
		traversalAllDir(start);
	}
}
/*
*同理,如果想遍历所有根目录,使用
File[] roots = File.listRoots();
*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值