2018_4_10 File I/O流 读写文件

一.         java程序如何访问文件属性?
Java API :java.io.File 类

使用.File 类,访问文件的属性

语法:File file=new File(String pathName);

例:File file=new File("C:\\test.txt");

注意:
A:一个“\”代表根目录,因为“\”有特殊意义,所以前面需要再加上一个“\”,代表转义字符。
B:将需要操作的文件 路径传给该对象,对象就可以通过一系列方法,对这个文件进行操作了。

File 类的常用方法,以及代码实例:

                File file=new File("D:/1.txt");//一般用左斜线    右斜线要用两个\\
		this.create(file);//调用下面的create()方法
		if(file.exists())
		{
			if(file.isFile())//判断是否为文件
			{
				System.out.println(file.getName());//文件名
				System.out.println(file.getAbsolutePath());//绝对路径
				System.out.println(file.getPath());//相对路径
				System.out.println(file.length());//文件字节长度
			}
			if(file.isDirectory())//判断是否为目录
			{
				System.out.println(file.isDirectory());
			}
		}
		else
		{
			System.out.println("文件不存在");
		}
public static void create(File file)
	{
		if(!file.exists())
		{
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
二、字节流与字符流概述

    读文件,是指把文件的数据读到内存中;(读入写出)

    写文件,是指把内存的数据写到文件中;

    流:是指一连串流动的字符,是以先进先出的方式发送和接收数据的通道

1、 字符流的由来
因为数据编码的不同,而有了对字符进行高效操作的流对象。本质其实就是基于字节流读取时,去查了指定的码表。

2、字节流和字符流的 区别
A: 读写单位不同:字节流以字节(8bit)为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。
B: 处理对象不同
字节流能处理所有类型的数据(如图片、avi等),而字符流只能处理字符类型的数据。

3、结论
只要是处理 纯文本数据,就优先考虑使用字符流。 除此之外都使用字节流。



三.字节流的读写:

1.读文件代码实例:


扫描二维码关注公众号,回复: 1933642 查看本文章
            try{
		        File file=new File(C:/123.txt);
			InputStream is =new FileInputStream(file);//输入流一共且只有2种构造方法
                //另一种构造InputStream is =new FileInputStream(C:/123.txt);
int length=is.read();//无参read()方法 一个一个读;while(length!=-1){System.out.print((char)length);//读数据用输入流length=is.read();}}catch(Exception e){e.printStackTrace();}finally{is.close();}
   下面这种通过把数据保存到数组中,再遍历数组的方式,效率更高
         InputStream is=null;
		try {
			is = new FileInputStream(file);
		
			byte[] bs=new byte[5];
			int length=is.read(bs);//is.read(bs)把读到的数据放到bs数组中   并返回 bs数组的长度  当长度为0时,返回-1
			while(length!=-1)
			{
				for(byte b:bs){
				    System.out.println((char)b);
				}
				length=is.read(bs);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			
				try {
					if(is!=null)
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
2.写文件代码实例:
            File file =new File("C:/123.txt");
		FileOutputStream fos=null;
		//FileOutputStream类共有3种构造方法,下面是它的其他两种构造方法:
		//FileOutputStream fos=new FileOutPutStream("C:/123.txt");
		//FileOutputStream fos=new FileOutPutStream(String name,boolean append);
		//第三种构造方法是独特的,当参数boolean值传true时,意思为写入的文件不会采取覆盖,而是叠加,原文件内容将得到保存
		try {
			 fos=new FileOutputStream(file);
			 String str="禾苗";
			 byte[] words=str.getBytes();
			 //写入文件
			 fos.write(words,0,words.length);
			 System.out.println("123.txt文件已经更新!");
			 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
				try {
					if(fos!=null)
						fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
3.读写字节流的几大步骤:
a.引入相关类,
       b.创建文件输入(输出)流对象;
c.利用文件流的方法读取(写入)文本文件的数据;
      d.关闭输入(输出)流对象

四.使用字符流读文件:

1.字符流读:

                Reader reader=null;
		try {
			reader=new FileReader("D:/134.txt");
			int length;
			length = reader.read();
			while(length!=-1)
			{
				System.out.println((char)length);
				length=reader.read();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			
				try {
					if(reader!=null){
						reader.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

2.效率更高的读:

		Reader reader=null;
		try {
			reader=new FileReader("D:/134.txt");
			StringBuffer sb=new StringBuffer();
			char[] ch=new char[5];
			int length;
			length = reader.read(ch);//把读到的数据存到数组中
			while(length!=-1)
			{
				for(char c:ch)
					System.out.println((char)c);
				length=reader.read(ch);
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			
				try {
					if(reader!=null){
						reader.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

3.最高效的读BufferedReader类:

                Reader reader=null;
		BufferedReader bfr=null;
		try {
			reader=new FileReader("D:134.txt");
			bfr=new BufferedReader(reader);
			String line=bfr.readLine();
			while(line!=null)
			{
				System.out.println(line);
				line=bfr.readLine();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
					bfr.close();
					reader.close();
			}
		}

五.字符流的写:

1.

                FileWriter wr=null; 
		try {
			wr=new FileWriter(new File("D:/134.txt"));
			wr.write(97);
			wr.flush();//刷新缓冲区
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
				try {
					if(wr!=null)
					wr.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
2. 最高效的方法BufferedWriter
                FileWriter fw=null;
		BufferedWriter bw=null;
		try{
			fw=new FileWriter("D:/123.txt");
			bw=new BufferedWriter(fw);
			bw.write("大家好");
			bw.write("呵呵");
			bw.newLine();//换行
			bw.write("哈哈");
			bw.newLine();
			bw.flush();
			fw.close();
			
			FileReader fr=new FileReader("D:/123.txt");
			BufferedReader br=new BufferedReader(fr);
			String line=br.readLine();
			while(line!=null)
			{
				System.out.print(line);
				line=br.readLine();
			}
		}catch(Exception e){
			
		}finally{
			try {
				bw.close();
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

六 :使用字节流类DataInputStream读(写)二进制文件:

DataInputStream(DataOutputStream)是FileInputStream(FileOutputStream)的子类,是FileInputStream(FileOutputStream)的扩展;

以下是代码实例,功能是:从一个二进制文件134.txt中读取数据,然后将数据写入另一个二进制文件1345.txt

                DataInputStream dis=null;
		DataOutputStream out=null;
		FileInputStream fis;
		try {
			//创建输入流对象
			fis = new FileInputStream("D:/134.txt");
			dis=new DataInputStream(fis);
			//创建输出流对象
			FileOutputStream outFile=new FileOutputStream("D:/1345.txt");
			out=new DataOutputStream(outFile);
			int temp;
			//读取文件并写入文件
			while((temp=dis.read())!=-1){
				out.write(temp);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				dis.close();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}








猜你喜欢

转载自blog.csdn.net/qq1043002305/article/details/79921504