Java基础Demo -- IO 文件读/写/拷贝/删除

 File、包装器InputStreamReader OutputStreamwriter、缓冲器BuffedReader BuffedWriter、的运用:

  • 创建目录、创建文件、
  • 检查是否目录以及目录是否存在、检查是否文件以及文件是否存在
  • 罗列目录下的所有文件和文件夹
  • 常用的文件内容中的行分隔符、系统默认根目录
import java.util.Random;
import java.io.*;

/**
* 这个测试类FileDemo.java文件存储在我的本地机器:F:\demo\java\io下面
    PushbackInputStream是对二进制流的处理,字符流下相对应的就是PushbackReader。可当作语法解析器来使用。    
	例1:从左向右扫描字符流"for(int i=0;i<10;i++)",扫描到"for"是不是就可以说是个关键字了呢?不行,说不定后面是"for1",那就是个变量而不是关键字了,知道看到"("才恍然大悟,哦,我可以安全地说“看到for关键字”了,但“(”还得归还给输入流,因为需要后面继续扫描。在上下文相关语言里,就更需要这种补偿机制。
	例2:在解析HTML文档的时候,我需要根据它的"meta"标签的"charset"属性来决定使用哪种字符集进行解析,但HTML可不是“charset”而是“<html>”开头的哦!所以需要通过PushbackInputStream缓冲前面一段内容,等取到字符集名称后在把读到的流全部归还,再用指定的字符集进行解析。
*/
public class FileDemo  
{
	public static void main(String[] args) 
	{
		try{

			String str = "www.baidu.com" ;		// 定义字符串

			ByteArrayInputStream bai = new ByteArrayInputStream(str.getBytes()) ;	// 实例化内存输入流

			PushbackInputStream push = new PushbackInputStream(bai) ;	// 从内存中读取数据

			System.out.print("读取之后的数据为:") ;

			int temp = 0 ; 

			while((temp=push.read())!=-1){	// 读取内容

				if(temp=='.'){	// 判断是否读取到了“.”

					push.unread(temp) ;	// 放回到缓冲区之中

					temp = push.read() ;	// 再读一遍

					System.out.print("(退回"+(char)temp+")") ;

				}else{

					System.out.print((char)temp) ;	// 输出内容

				}

			}	

			System.out.println("\r\n************");

			System.out.println("user.dir "+System.getProperty("user.dir")); //user.dir指定了当前目录 
			System.out.println("user.home "+System.getProperty("user.home"));//user.home指定了用户根目录
			
			System.out.println((new File("/")).getAbsolutePath()); //当前根目录"/"的全路径

			String filepath = "/user/user2/";
			String filename = "dindoa.txt";
			String filepathname = filepath + filename;

			File fQ = new File(filepathname);	//File既可以包装文件
			File fPath = new File(filepath);	//File也可以包装文件夹
			File fName = new File(filename);	//File包装当前目录下的文件


			//文件是否存在
			System.out.println( filepathname + " exists is " + (fQ.exists() ? true : false) );

			//文件的内容长度
			/**
			*示例文件dingwei.txt内容(文件编码格式ANSI) 一个英文字母一个字节,一个中文两个字节,转义字符一个字节(例如:\r\n算两个字节)
			*
			*asdfghjk\r\n
			*我们的世界\r\n
			*
			*注意上方的内容中如果打开文本文件是看不到\r\n的,我是为了示例的方便故意写出来的
			*/
			System.out.println( filepathname + " file.length is " + fQ.length() ); 
			
			System.out.println( filepathname + " fileinputstream.available is " + (new FileInputStream(fQ)).available() );

			//创建目录(目录不存在则创建,否则啥也不做)
			fPath.mkdirs();

			//创建文件(文件不存在则创建,否则啥也不做)
			fQ.createNewFile();

			//File封装的是文件?目录
			System.out.println( filepathname + " isFile: " + fQ.isFile() ); //是文件,文件全路径
			System.out.println( "user.dir "+System.getProperty("user.dir") +" "+ filename + " isFile: " + fName.isFile() );  //当前目录下并不存在该文件
			System.out.println( filepath + " isDirectory: " + fPath.isDirectory() ); //是目录,

			System.out.println( filepathname + " getName: " + fQ.getName() ); //文件名称
			System.out.println( filepathname + " getParent: " + fQ.getParent() ); //父目录
			System.out.println( filepathname + " getPath: " + fQ.getPath() ); //File封装的字符串形式
			System.out.println( filepathname + " getAbsolutePath: " + fQ.getAbsolutePath() ); //文件全路径的全称

			//文件重命名
			System.out.println( fQ.renameTo( new File(fPath,"rename"+((new Random()).nextInt(100))+".txt"))  ); //文件重命名

			//获取绝对路径
			System.out.println( filepathname + " absolutePath is : " + fQ.getAbsolutePath() );

			//获取所属目录
			File parent = fQ.getParentFile();		

			
			//目录下的所有直接孩子文件和孩子文件夹(不递归)
			File[] fArray = parent.listFiles();
			for(File k: fArray)
				System.out.println(k.getName());

			String[] fs = parent.list();
			for(String j: fs)
				System.out.println(j);

			//带有过滤功能的目录下的所有直接孩子文件和孩子文件夹(不递归)
			File[] filterArray = parent.listFiles( new FilenameFilter(){
					public boolean accept(File dir,String name){
						return name.endsWith(".txt");
					}
				});
			for(File n: filterArray)
				System.out.println(n.getName());
				


			//写文件
			File tmpFile = new File(filepath,"tmp.txt");
			if( !tmpFile.exists() || !tmpFile.isFile() ){
				tmpFile.createNewFile();
			}

			try( BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile,true))) ){
				bw.write("nihao");bw.newLine();
				bw.write("hello");bw.newLine();
				bw.write("world");bw.newLine();
				bw.flush();
			}catch(Exception e){}

			//读文件
			StringBuffer sb = new StringBuffer();
			try( BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(tmpFile))) ){
				String line ;
				do{
					line = br.readLine();
					if(null!=line) sb.append(line);
				}while(null!=line);
			}catch(Exception e){
			}
			System.out.println(tmpFile.getName()+" is "+sb.toString());

			//文件拷贝
			File tmpFileBak = new File(filepath,"tmpback.txt");
			if( !tmpFileBak.exists() || !tmpFileBak.isFile() ){
				tmpFileBak.createNewFile();
			}
			try( BufferedReader br2 = new BufferedReader(new InputStreamReader(new FileInputStream(tmpFile)));
				 BufferedWriter bw2 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFileBak)))){
				StringBuffer sb2 = new StringBuffer();
				String line2;
				do{
					line2 = br2.readLine();
					if(null!=line2) sb2.append(line2).append(System.getProperty("line.separator"));
				}while(null!=line2);

				bw2.write(sb2.toString());
				bw2.append('c');
				bw2.flush();

			}catch(Exception e){}

			//删除文件
			System.out.println(tmpFileBak.getAbsolutePath()+" deleted is "+tmpFileBak.delete());

			//删除目录(目录只能一级一级的删除)
			System.out.println("delete not empty directory /user/user2 is : "+(new File("/user/user2")).delete() );
			System.out.println("delete empty directory /user/user2/job is : "+(new File("/user/user2/job")).delete() );
			
			
			/**
			*文件内容中的行分隔符
			*
			*Mac:     每行结尾"/r" 回车
			*Unix:    每行结尾"/n" 换行
			*Windows: 每行结尾"\r\n" 回车换行

			*Unix/Mac系统下的文件在Windows里打开,所有文字会变成一行
			*Windows里的文件在Unix/Mac下打开,在每行的结尾可能会多出一个^M符号
			*/
			if (System.getProperty("line.separator").equals("\r\n")) {    
				System.out.println("\\r\\n is windows's line.separator");    
			} 
			else if (System.getProperty("line.separator").equals("/r")) {    
				System.out.println("/r is for Mac");    
			} 
			else if (System.getProperty("line.separator").equals("/n")) {    
				System.out.println("/n is for Unix/Linux");    
			}

		}catch(Exception e){}
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值