Java IO学习

package file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Writer;

import org.junit.Test;

public class FileTest {
	
	@Test
	public void Test01() {
		// File dir = new File("aaa/bbb");
		// dir.mkdirs();

		File file = new File("abc.txt");
		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void Test02() {
		//File f = new File("D:\\temp\\hello.txt");
		File f = new File("abc.txt");
		try {
			f.createNewFile();
			System.out.println("文件创建成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println(File.separator);
		System.out.println(File.pathSeparator);
		
		System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径
		/*
		附:System.getProperty()中的字符串参数如下:
		System.getProperty()参数大全
		# java.version						Java Runtime Environment version
		# java.vendor						Java Runtime Environment vendor
		# java.vendor.url					Java vendor URL
		# java.home                         Java installation directory
		# java.vm.specification.version		Java Virtual Machine specification version
		# java.vm.specification.vendor    	Java Virtual Machine specification vendor
		# java.vm.specification.name      	Java Virtual Machine specification name
		# java.vm.version                   Java Virtual Machine implementation version
		# java.vm.vendor                    Java Virtual Machine implementation vendor
		# java.vm.name                      Java Virtual Machine implementation name
		# java.specification.version        Java Runtime Environment specification version
		# java.specification.vendor         Java Runtime Environment specification vendor
		# java.specification.name           Java Runtime Environment specification name
		# java.class.version                Java class format version number
		# java.class.path                   Java class path
		# java.library.path                 List of paths to search when loading libraries
		# java.io.tmpdir                    Default temp file path
		# java.compiler                     Name of JIT compiler to use
		# java.ext.dirs                     Path of extension directory or directories
		# os.name                           Operating system name
		# os.arch                           Operating system architecture
		# os.version                       	Operating system version
		# file.separator                    File separator ("/" on UNIX)
		# path.separator                  	Path separator (":" on UNIX)
		# line.separator                   	Line separator ("\n" on UNIX)
		# user.name                        	User's account name
		# user.home                        	User's home directory
		# user.dir                         	User's current working directory 
		*/
		
		File directory = new File("");//设定为当前文件夹
		
		//File directory = new File(".");
		//File directory = new File("..");
		/*
		File.getCanonicalPath()和File.getAbsolutePath()大约只是对于new File(".")和new File("..")两种路径有所区别。
		# 对于getCanonicalPath()函数,“."就表示当前的文件夹,而”..“则表示当前文件夹的上一级文件夹
		# 对于getAbsolutePath()函数,则不管”.”、“..”,返回当前的路径加上你在new File()时设定的路径
		# 至于getPath()函数,得到的只是你在new File()时设定的路径
		*/
		try{
		    System.out.println(directory.getCanonicalPath());//获取标准的路径
		    System.out.println(directory.getAbsolutePath());//获取绝对路径
		}catch(Exception e){}
	}

	@Test
	public void Test03() {
		String separator = File.separator;
		String fileName = "D:" + separator + "temp" + separator + "hello.txt";
		File f = new File(fileName);
		if (f.exists()) {
			System.out.println(f.getName() + "已存在,现在开始删除文件");
			f.delete();
		} else {
			System.out.println("文件不存在");
		}
	}

	/**
	 * 创建一个文件夹
	 * */
	@Test
	public void Test04() {
		String directoryFileName = "D:\\temp\\dir";
		File dir = new File(directoryFileName);
		dir.mkdir();
		System.out.println("目录创建成功!");
	}

	/**
	 * 使用list列出指定目录的全部文件夹与文件名称
	 * */
	@Test
	public void Test05() {
		String fileName = "D:\\";
		File f = new File(fileName);
		// String[] str=f.list();//

		File[] str = f.listFiles();// 列出完整路径
		for (int i = 0; i < str.length; i++) {
			System.out.println(str[i]);
		}
	}

	@Test
	public void Test06() {
		// String fileName="D:"+File.separator;
		String fileName = "D:\\";
		File f = new File(fileName);
		if (f.isDirectory()) {
			System.out.println("YES");
		} else {
			System.out.println("NO");
		}
	}

	@Test
	public void Test07() {
		String fileName = "D:\\";
		File file = new File(fileName);
		printFile(file);
	}

	public void printFile(File file) {
		if (file != null) {
			if (file.isDirectory()) {
				File[] fileArrays = file.listFiles();
				if (fileArrays != null) {
					for (File f : fileArrays) {
						printFile(f);
					}
				}
			} else {
				System.out.println(file);
			}
		}
	}

	// 用RandomAccessFile想指定文件输出内容
	@Test
	public void Test08() throws IOException {
		File f = new File("abc.txt");
		RandomAccessFile demo = new RandomAccessFile(f, "rw");
		demo.writeBytes("asdsad");
		demo.writeBytes("张三");
		demo.writeInt(12);
		demo.writeBoolean(true);
		demo.writeChar('A');
		demo.writeFloat(1.21f);
		demo.writeDouble(12.123);
		demo.close();
	}

	/**
	 * 字节流 向文件中写入字符串
	 * */
	@Test
	public void Test09() throws IOException {
		File f = new File("abc.txt");
		FileOutputStream fop = new FileOutputStream(f);
		String text = "想要输出的内容";
		byte[] b = text.getBytes();
		fop.write(b);
		fop.close();
	}

	/**
	 * 字节流 向文件中一个字节一个字节的写入字符串
	 * */
	@Test
	public void Test10() throws IOException {
		File f = new File("abc.txt");
		FileOutputStream fop = new FileOutputStream(f);
		String text = "一个字节一个字节地输出内容";
		byte[] b = text.getBytes();
		for (int i = 0, length = b.length; i < length; i++) {
			fop.write(b[i]);
		}
		fop.close();
	}

	/**
	 * 字节流 向文件中追加新内容:
	 * */
	@Test
	public void Test11() throws IOException {
		File f = new File("abc.txt");
		// if <code>true</code>, then bytes will be written to the end of the
		// file rather than the beginning
		OutputStream out = new FileOutputStream(f, true);
		String str = "\r\n追加新文字";// window环境中换行符为\r\n
		byte[] b = str.getBytes();
		for (int i = 0, length = b.length; i < length; i++) {
			out.write(b[i]);
		}
		out.close();
	}

	/**
	 * 字节流 读文件内容
	 * */
	@Test
	public void Test12() throws IOException {
		File f = new File("abc.txt");
		System.out.println("文件大小为"+f.length());
		InputStream in = new FileInputStream(f);
//		byte[] b = new byte[1024];
//		in.read(b);
//		in.close();
//		System.out.println(new String(b));

		
//		byte[] b = new byte[1024];
//		int len=in.read(b);
//        in.close();
//        System.out.println("读入长度为:"+len);
//        System.out.println(new String(b,0,len));
		
		
//		byte b[] = new byte[(int)f.length()] ;// 数组大小由文件决定  
//        for(int i=0,length=b.length;i<length;i++){  
//            b[i] = (byte)in.read() ;// 读取内容 
//            System.out.print("  "+b[i]);
//        }
//        in.close() ;// 关闭输出流\  
//        System.out.println(new String(b)) ;// 把byte数组变为字符串输出  
		
		byte b[] = new byte[(int)f.length()] ;// 数组大小由文件决定  
        int len = 0 ; 
        int temp = 0 ;// 接收每一个读取进来的数据  
        while((temp=in.read())!=-1){  
            // 表示还有内容,文件没有读完  
            b[len] = (byte)temp ;  
            len++ ;  
        }  
        // 第4步、关闭输出流  
        in.close() ;// 关闭输出流\  
        System.out.println("内容为:" + new String(b,0,len));// 把byte数组变为字符串输出  
	}
	
	/*
	 *使用字符流Writer输出内容 
	 */
	@Test
	public void Test13() throws Exception{    // 异常抛出,不处理  
        // 第1步、使用File类找到一个文件  
		File f = new File("abc.txt");// 声明File对象  
        // 第2步、通过子类实例化父类对象  
        Writer out = null ; // 准备好一个输出的对象  
        out = new FileWriter(f)  ;  // 通过对象多态性,进行实例化  
        // 第3步、进行写操作  
        String str = "Hello World!!!" ;// 准备一个字符串  
        out.write(str) ;// 将内容输出,保存文件  
        // 第4步、关闭输出流  
        out.close() ; // 关闭输出流  
    }  
	
	
	/*
	 *使用字符流Writer向指定文件追加内容
	 */
	@Test
	public void Test14() throws Exception{    // 异常抛出,不处理  
        // 第1步、使用File类找到一个文件  
		File f = new File("abc.txt");// 声明File对象  
        // 第2步、通过子类实例化父类对象  
        Writer out = null ; // 准备好一个输出的对象  
        out = new FileWriter(f,true)  ;  // 通过对象多态性,进行实例化  
        // 第3步、进行写操作  
        String str = "Hello World!!!" ;// 准备一个字符串  
        out.write(str) ;// 将内容输出,保存文件  
        // 第4步、关闭输出流  
        out.close() ; // 关闭输出流  
    } 
	
	/*
	 *使用字符流Reader读入内容 
	 */
	@Test
	public  void Test15() throws IOException{    // 异常抛出,不处理  
        // 第1步、使用File类找到一个文件  
		File f = new File("abc.txt");// 声明File对象  
        // 第2步、通过子类实例化父类对象  
        Reader input = null ;   // 准备好一个输入的对象  
        input = new FileReader(f)  ;    // 通过对象多态性,进行实例化  
        // 第3步、进行读操作  
        char c[] = new char[1024] ;     // 所有的内容都读到此数组之中  
        int len = input.read(c) ;       // 读取内容  
        // 第4步、关闭输出流  
        input.close() ;                // 关闭输出流  
        System.out.println("内容为:" + new String(c,0,len)) ;  // 把字符数组变为字符串输出  
    }  
	
	
	/*
	 *使用字符流Reader读入内容 
	 */
	@Test
	public  void Test16() throws IOException{    // 异常抛出,不处理  
        // 第1步、使用File类找到一个文件  
		File f = new File("abc.txt");// 声明File对象  
        // 第2步、通过子类实例化父类对象  
        Reader input = null ;   // 准备好一个输入的对象  
        input = new FileReader(f)  ;    // 通过对象多态性,进行实例化  
        // 第3步、进行读操作  
        char c[] = new char[1024] ;     // 所有的内容都读到此数组之中  
        int temp = 0 ;  // 接收每一个内容  
        int len = 0 ;       // 读取内容  
        while((temp=input.read())!=-1){  
            // 如果不是-1就表示还有内容,可以继续读取  
            c[len] = (char)temp ;  
            len++ ;  
        }  
        // 第4步、关闭输出流  
        input.close() ;                     // 关闭输出流  
        System.out.println("内容为:" + new String(c,0,len)) ;  // 把字符数组变为字符串输出 
    }  
	
	/*
    InputStreamReader将字节流转换为字符流。是字节流通向字符流的桥梁。如果不指定字符集编码,该解码CharsetDecoder过程将使用平台默认的字符编码,如:GBK。
	是Reader的子类,将输入的字节流变为字符流,即将一个字节流的输入对象变为字符流的输入对象。
	构造方法:
        InputStreamReader isr = new InputStreamReader(InputStream in);//构造一个默认编码集的InputStreamReader类
        InputStreamReader isr = new InputStreamReader(InputStream in,String charsetName);//构造一个指定编码集的InputStreamReader类。
		参数 in对象通过 InputStream in = System.in;获得。//读取键盘上的数据。
		或者    InputStream in = new FileInputStream(String fileName);//读取文件中的数据。可以看出FileInputStream 为InputStream的子类。
		主要方法:int read();//读取单个字符。
		int read(char []cbuf);//将读取到的字符存到数组中。返回读取的字符数。
	*/
	@Test
	public void Test17() throws IOException {
		/** 
         * 没有缓冲区,只能使用read()方法。 
        */
		//读取字节流
//		InputStream in = new FileInputStream("abc.txt");//读取文件的数据。  
//        //将字节流向字符流的转换。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节.  
//        InputStreamReader isr = new InputStreamReader(in);//读取 
		InputStreamReader isr = new InputStreamReader(
				new FileInputStream("abc.txt"), "UTF-8");//将读入的字节流以UTF-8的形式转化为字符流
				//System.in, "UTF-8");//从控制台读入字节流,并以UTF-8的形式转化为字符流
		char[] cbuf = new char[1024];

//		isr.read(cbuf);
//		System.out.println(new String(cbuf));
		int len = isr.read(cbuf);
		System.out.println(new String(cbuf,0,len));
		isr.close();
	}
	
	
	@Test
	public void Test1701() throws IOException {
		/** 
         * 使用缓冲区 可以使用缓冲区对象的 read() 和  readLine()方法。  
        */
		//读取字节流
		InputStream in = new FileInputStream("abc.txt");//读取文件的数据。  
        //将字节流向字符流的转换。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节.  
        InputStreamReader isr = new InputStreamReader(in);//读取  

        //创建字符流缓冲区  
        BufferedReader bufr = new BufferedReader(isr);//缓冲  
        String line = null;  
        while((line = bufr.readLine())!=null){  
            System.out.println(line);  
        }  
		isr.close();
	}
	
	
	
	/*
	OutputStreamWriter将字符流转换为字节流。是字符流通向字节流的桥梁。如果不指定字符集编码,该编码CharsetEncoder过程将使用平台默认的字符编码,如:GBK。
	是Writer的子类,将输出的字符流变为字节流,即将一个字符流的输出对象变为字节流输出对象。
	构造方法:
		OutputStreamWriter osw = new OutputStreamWriter(OutputStream out);//构造一个默认编码集的OutputStreamWriter类
		OutputStreamWriter osw = new OutputStreamWriter(OutputStream out,String charsetName);//构造一个指定编码集的OutputStreamWriter类。
		参数 out对象通过 InputStream out = System.out;获得。//打印到控制台上。
		或者InputStream out = new FileoutputStream(String fileName);//输出到文件中。可以看出FileoutputStream 为outputStream的子类。
		主要方法:
				void write(int c);//将单个字符写入。
				viod write(String str,int off,int len);//将字符串某部分写入。
				void flush();//将该流中的缓冲数据刷到目的地中去
	*/
	@Test
	public void Test18() throws IOException {
		OutputStreamWriter osw = new OutputStreamWriter(
				new FileOutputStream("abc.txt"), "UTF-8");//指定输出位置
		BufferedWriter bw = new BufferedWriter(osw);
		bw.write("信义仁爱VS信義仁愛");//将字符写出到abc.txt文件中
		bw.flush();
		bw.close();
	}
	
	
	
	/*
	OutputStreamWriter将字符流转化为字节流
	*/
	@Test
	public void Test19() throws IOException {
		OutputStream out = System.out;//打印到控制台  
		//OutputStream out = new FileOutputStream("D:\\demo.txt");//打印到文件  
		OutputStreamWriter osr = new OutputStreamWriter(out);//输出  
		//OutputStreamWriter osr = new OutputStreamWriter(new FileOutputStream("D:\\demo.txt"));//两句可以综合到一句。  
		//int ch = 97;//a  
		//int ch = 20320;
		//osr.write(ch);  
		String str = "你好吗?";//要输出的字符  
		osr.write(str);
		osr.flush();
		osr.close();  
	}
	
	/*
	*将一个图片文件复制到另一个地方 
	*/
	@Test
	public void Test20(){
		FileInputStream input = null;
		FileOutputStream output = null;
	try {
	    input = new FileInputStream(new File("evil_korea.gif"));
	    output = new FileOutputStream("evil_korea_new.gif");
	    int a;
	    while ((a = input.read()) != -1) {
	          output.write(a);
	    }
	    output.flush();
	} catch (FileNotFoundException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}finally {
	    try {
	        output.close();
	        input.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}
	}
}



参考链接1:http://blog.youkuaiyun.com/liuhenghui5201/article/details/8292552

参考链接2:http://blog.youkuaiyun.com/hippoppower/article/details/4547876

测试代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值