JAVAIO笔记

思维导图

File类

  • 实例化 new File(path);
  • File.separator 分隔符

创建文件的常规做法👇,先问文件的目录存不存在。还有,如果不确定文件是否存在,要问一下文件是否存在,如果文件已经存在了那就不会创建新文件。

package cn.io;

import java.io.File;
import java.io.IOException;

public class FileDemo {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		String path = "d:"+File.separator+"xx"+File.separator+"dd.txt";
		File dd = new File(path);
		if(dd.getParentFile().exists()) {
			dd.createNewFile();
		}else {
			dd.getParentFile().mkdirs();
			dd.createNewFile();
		}
	}

}

下面程序的小递归要注意一下👇。

package cn.suyuesheng.io;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class FileDemo {

	public static void main(String[] args) throws IOException, InterruptedException {
		long startTime = System.currentTimeMillis();
		// TODO Auto-generated method stub
		System.out.println(File.pathSeparator);
		System.out.println(File.separator);
		//创建文件
		String path = "f:"+File.separator+"a.txt";
		//为了可移植性,务必用File.separator
		File  a = new File(path);//给出文件路径
		a.createNewFile(); //创建文件
		
		Process p=Runtime.getRuntime().exec("notepad.exe");
		Thread.sleep(400);
		p.destroy();
		//删除一个文件
		//a.delete();//这样做有问题,应该先询问是否存在
		if(a.exists()) {
			a.delete();
		}
		//练习,如果存在‘e:\\hello.doc’就删除他,否则就创建‘f:\\c.txt’
		{
			String patha = "e:"+File.separator+"hello.doc";
			String pathb = "f:"+File.separator+"c.txt";
			if(new File(patha).exists()) {
				new File(patha).delete();
			}else {
				new File(pathb).createNewFile();
			}
		}//f盘下创建了c.txt
		{//创建文件夹
			String patha = "e:"+File.separator+"suyueshengjava"+File.separator+"kk";
			File ff = new File(patha);//得到文件路径
			if(ff.getParentFile().exists()) {//如果父路径存在
				ff.mkdir();//创建文件夹
				//创建多级文件夹用mkdirs
			}
			ff.delete();
			
		}
		{//list 列出文件夹中的文件名称 返回一个String[]
			String patha = "e:"+File.separator+"suyueshengjava"+File.separator+"a.txt";
			System.out.println(patha);
			new File(patha).createNewFile();
			//展示目录
			String pathb = "d:"+File.separator;
			System.out.println(Arrays.toString(new File(pathb).list()));
		}
		{//listFiles 列出每一个文件的完整路径 返回一个File[]
			String pathb = "d:"+File.separator;
			File[] ll = (new File(pathb)).listFiles();
			for(File x:ll) {
				System.out.println(x);
			}
		}
		{
			//判断是否是目录
			String pathb = "d:"+File.separator;
			System.out.println(new File(pathb).isDirectory());
		}
		{
			//文件大小
			String patha = "e:"+File.separator+"qq.xml";
			File ff = new File(patha);
			if(ff.isFile()) {
				System.out.println(ff.length());
			}
		}
		{//文件最后的修改日期  lastModified
			String patha = "e:"+File.separator+"qq.xml";
			File ff = new File(patha);
			System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS").format(new Date(ff.lastModified())));
			
		}
		System.out.println(System.currentTimeMillis()-startTime);
		String thePath = "d:"+File.separator;
		File thePathFile = new File(thePath);
		print(thePathFile);
		System.out.println(System.currentTimeMillis()-startTime);
	}
	//File小递归
	public static void print(File file) {
		if(file.isDirectory()) {
			File[] tf = file.listFiles();
			if(tf!=null) {
				for(File x : tf) {
					print(x);
				}
			}
		}
		System.out.println(file.getPath());
	}
}

文件的修改

有字节流和字符流,字符流只能输入输出带字的文件,字节流可以读取文件的字节,所以文件复制的操作是要字节流来的。

简单字节流

如下面代码所示OutputStream是一个抽象类。实例化只能实例化FileOutputStream。
参数是File。如果该文件没有,就会自动创建。

        String path = "d:"+File.separator+"xx"+File.separator+"dd.txt";
		File dd = new File(path);
		OutputStream output = new FileOutputStream(dd);//如果文件没有就创建文件

OutputStream的几个方法,write的操作本质上就是写入字节
在这里插入图片描述
InputStream的input.read()是一个一个字节的读取,返会int。其实就是字节。
在这里插入图片描述
read(byte[] b)返回的int是读入数据的长度。字节操作的时候文件的大小恰好就是byte数组的长度。

package cn.suyuesheng.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ZiJie {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		String a = "d:"+File.separator+"xx"+File.separator+"bb.txt";
		System.out.println(a);
		File bb = new File(a);
		if(!bb.getParentFile().exists()) {
			bb.getParentFile().mkdirs();
			bb.createNewFile();
		}else {
			bb.createNewFile();
		}
		{
			OutputStream out = new FileOutputStream(bb);
			String aa= "hello world";
			byte b[] = aa.getBytes();
			out.write(b);
			out.close();
			System.out.println(bb.length());
		}
		{//另一种方法
			OutputStream oo = new FileOutputStream(bb);
			byte b[] = "jjkkjkjkjk".getBytes();
			for(byte bin:b) {
				oo.write(bin);
			}
			oo.close();
			
		}
		{//追加
			OutputStream out = new FileOutputStream(bb,true);//追加
			byte n[] = "你好".getBytes();
			out.write(n);
			//换行追加
			byte nn[]= "\r\n hello world。现代操作系统的内存管理都具有分页机制,而内存页的大1874 年 6 月穆索尔斯基写下钢琴组曲《图画展览会》,灵感来自于一次画作展览会,画展上的作品是穆索尔斯基一位已逝世的朋友、俄罗斯著名艺术家、建筑师维克托 · 阿里山大罗维奇 · 哈特曼所画。穆索尔斯基借此作品,抒发了他对友人怀念的真切情感。在和声手法、曲式结构和钢琴织体方面也有着新的探索。".getBytes();
			out.write(nn);
		}
		{//读写
			InputStream input = new FileInputStream(bb);
			byte[] c = new byte[(int)bb.length()];
			System.out.println(new String(c));
			input.read(c);
			System.out.println(new String(c));
			input.close();
			
		}
		{//知道文件大小,循环写入
			InputStream input = new FileInputStream(bb);
			System.out.println(bb.length());
			System.out.println((int)bb.length());
			byte c[] = new byte[(int)bb.length()];
			byte cc[]=null;
			for(int i=0;i<c.length;i++) {
				c[i]=(byte)input.read();
			}
			input.close();
			System.out.println(new String(c));
		}
		{
			//不知道文件大小
			InputStream input = new FileInputStream(bb);
			byte c[] = new byte[1024];
			int len =0;//角标
			int temp=0;
			while((temp=input.read())!=-1) {
				c[len]=(byte)temp;
				len++;
			}
			input.close();
			System.out.println(new String(c,0,len));
		}
		String jkPath = "d:"+File.separator+"xx"+File.separator+"jk.txt";
		File jk = new File(jkPath);
		if(!jk.exists()) {
			System.out.println("erroe");
		}
		{
			InputStream input = new FileInputStream(jk);
			System.out.println(jk.length());
			byte[] c = new byte[(int)jk.length()];
			input.read(c);
			System.out.println("["+new String(c,"utf-8")+"]");//设置编码格式
		}
		{
			
		}
	}

}

案例,复制文件
package cn.suyuesheng.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


//平时用字节流
public class CopyDemo {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		long start = System.currentTimeMillis();
		if(args.length!=2) {
			System.out.println("文件个数不对");
			System.exit(1);
		}
		File A = new File(args[0]);
		File B = new File(args[1]);
		if(!A.exists()) {
			System.out.println("源文件不存在");
			System.exit(1);
		}
		if(!B.getParentFile().exists()) {
			B.getParentFile().mkdirs();
		}
		OutputStream out = new FileOutputStream(B);
		InputStream input = new FileInputStream(A);
		int temp=0;
		byte[] bb = new byte[2048];
		while((temp=input.read(bb))!=-1) {
			out.write(bb,0,temp);
		}
		out.close();
		input.close();
		long end =System.currentTimeMillis();
		System.out.println("花费"+(end-start)+"毫秒");
	}

}

根据此案例可以看出read(byte[] b)也是递进向前的,和read()相似,图标向前走。

简单字符流

WriterReader一样是抽象类 ,实例化需要借助FileWriterFileReader
在这里插入图片描述
👆,可以看到Writer类的write方法可以写入单一字符(由byte字节编码而成),和字符集,和字符串
在这里插入图片描述
read()没有参数的时候读取单个字符,返回单个字符的编码

package cn.suyuesheng.io;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class ZiFu {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		String mmpath="d:"+File.separator+"xx"+File.separator+"mm.txt";
		File mm = new File(mmpath);
		if(mm.getParentFile().exists()) {
			mm.createNewFile();
		}else {
			mm.getParentFile().mkdirs();
		}
		Writer wmm = new FileWriter(mm,true);
		{
			String a="你好";
			wmm.write(a);//已字符串形式传入
		}
		{
			char a[] = "\r\nhello world".toCharArray();//字符数组形式
			wmm.write(a);
		}
		{
			wmm.write(1);
		}
		{
			byte[] c = "gggdsfs".getBytes();
			for(int i=0;i<c.length;i++) {
				wmm.write(c[i]);//整数类型传入
			}
		}
		{
			//reader
			Reader rmm = new FileReader(mm);
			char[] x= new char[1024];
			int cc = rmm.read(x);
			System.out.println(new String(x,0,cc));//这样会产生垃圾
		}
		System.out.println(">_______________");
		{//reader 循环方式
			Reader rmm = new FileReader(mm);
			int len =0;
			int temp;
			char cc[] = new char[1024];
			while((temp=rmm.read())!=-1) {
				cc[len++]=(char)temp;
			}
			System.out.println(new String(cc,0,len));
		}
		wmm.close();
	}

}

字符流和字节流的区别,字符流使用了缓存区,也就是说字符流不close不执行。当然也可以强制性清空缓存区,flush()方法来迫使字符流执行
字符流和字节流,能使字节流就使字节流。因为字节流范围广

OutputStreamWriter InputStreamReader发挥桥梁作用

打印流

在这里插入图片描述
打印流分为字符打印和字节打印。
PrintStreamPritntWriter基本相似,唯一区别就是PritntWriter在接收File,文件地址,Writer的基础上,可以接收OutputStream(接收这个可以设置自动刷新) 别忘了close
打印流的方便之处在于可以输出的类型很全。不出意外情况,能使打印流就使打印流。

package cn.suyuesheng.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

public class PrintStreamDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String path = "d:" + File.separator + "xx" + File.separator + "dd.txt";
		File dd = new File(path);
		if (dd.getParentFile().exists()) {// 创建文件
			try {
				dd.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			dd.getParentFile().mkdirs();
			try {
				dd.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			;
		}
		OutputStream outPut = null;
		try {
			outPut = new FileOutputStream(dd, true);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		;
		try {
			outPut.write(("\r\n"+path).getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 使用打印流
		PrintStream printD = null;
		printD = new PrintStream(outPut);// 如果构造方法里面写的是文件名称,那就不会是追加写,会是覆盖写
		printD.print(12.2343);
		// 格式化输出 了解
		printD.printf("\r\n年龄:%d;姓名:%s。", 14, "小張");
		printD.close();
		// Stirng類的格式化輸出
		System.out.println(String.format("hello %s", "校長"));
	}

}

BufferedReaderScanner

俩都是管输入的。
第一个区别java.util.Scannerjava.io.BufferedReader 包不一样。
BufferedReader的特殊方法是readLine。一次读一行,返回String类

package cn.suyuesheng.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class BuffereredReaderDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//讀取文件更加方便
		//標準的讀取鍵盤内容範例
		BufferedReader buf =null;
		buf = new BufferedReader(new InputStreamReader(System.in));
		String str=null;
		try {
			str=buf.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};
		System.out.println(str);
		//循環輸入
		System.out.println("請輸入整數,一位或者三位");
		boolean flag = true;
		while(flag) {
			try {
				str = buf.readLine();
				if(str.matches("\\d{1,3}")) {
					System.out.println(str);
					flag=false;
				}else {
					System.out.println("輸入的格式不符合標準");
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		//讀取文件   這是讀取字符文件的標準做法
		File dd = new File("d:"+File.separator+"xx"+File.separator+"dd.txt");
		BufferedReader pp =null;
		try {
			 pp= new BufferedReader(new FileReader(dd));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			System.out.println(pp.readLine());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		str=null;
		try {
			while((str=pp.readLine())!=null) {
				System.out.println(str);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

ScanneruseDelimiter可以设置分隔符(默认是空格和换行),用hasNext()和next()方法。Scanner的构造方法里面,能接收的参数也多,且能设置字符编码。而BufferedReader的构造方法只能接收reader,还不能设置字符编码
编码详解

在这里插入图片描述

package cn.suyuesheng.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class ScannerDemo {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		File bb = new File("d:" + File.separator + "xx" + File.separator + "xx.txt");
		Scanner scan = null;

		try {
			scan = new Scanner(new FileInputStream(bb), "utf-8");
			scan.useDelimiter("\n");// 设置分隔符,默认的里面有空格
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		while (scan.hasNext()) {

			try {
				System.out.println(new String(scan.next().getBytes(), "gbk"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		// 获取键盘输入
		System.out.print("情书入");
		Scanner cc = new Scanner(System.in);
		cc.useDelimiter("\n");
		System.out.println(cc.next());
		cc = new Scanner(System.in);
		String str = null;
		Date date = null;
		if (cc.hasNext("\\d{4}-\\d{2}-\\d{2}")) {
			str = cc.next("\\d{4}-\\d{2}-\\d{2}");
			date = new SimpleDateFormat("yyyy-MM-dd").parse(str);
			System.out.println(date);
		} else {
			System.out.println("cuo");
			System.out.println(cc.next());
		}
		boolean cf = true;
		while(cf) {
			System.out.print("循環輸入");
			System.out.println(cc.next());
		}
	}

}

在这里插入图片描述
ByteArrayInputStreamByteArrayOutputStream是内存流,把io的操作带入了内存里面。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值