JAVA基础(25)-Java IO流

目录

File类型

IO流(Input,Output)

1、字节流

缓冲流   

数据字节流

对象流

2、字符流

缓冲流(数据)

转换流

文件字符流


File类型

       概念:可以用来创建,删除文件/目录,还可以查看文件/目录的属性信息。但是不可以修改文件里的数据。如果需要修改,应该使用输入/输出流。
       常用构造器:
              File(String pathname)   创建一个指定路径的File对象
              File(File parent,String child)    在指定parent路径下,创建一个child的file对象
              File(String parent,String child)    在指定parent路径下,创建一个child的file对象
              --路径
                       绝对路径:是从根目录开始写的路径window: 从盘符开始书写: D:\a\f1.txt   D:\a\b
                                        linux:   /home/scott/f1.txt       /home/scott        
                       相对路径: 相对某一文件/目录的路径,不是从根路径书写。
                          
       常用方法:
              boolean exists()    判断指定的路径是否存在
              boolean isFile()    判断指定路径是不是文件
              boolean isDirectory()    判断指定路径是不是目录
              String getName()    获取文件/目录名称
              long lastModified()    获取文件/目录的最后修改时间
              boolean isAbsolute()    判断指定路径是不是绝对路径
              String getAbsolutePath()    获取绝对路径
              String getParent()    获取父目录的路径
              long length()    获取文件大小   
       文件/目录创建方法:
              boolean createNewFile()    创建文件
              boolean mkdir()    创建目录
              boolean mkdirs()    创建多级目录
       文件/目录的删除方法:
              boolean delete()    可以删除文件,删除目录时,需要目录下没有文件或子目录
              File[] listFiles()    获取目录里的file对象

练习代码

    /**
     *  ..  :上一级目录(父目录)
     *  .   :当前目录
     *  
     *  File构造器中的路径
     *     如果是相对路径,相对于项目名路径
     */       
	public static void main(String[] args) throws Exception {
		/* File(File parent,String child)*/
		File file = new File(".");
		File f1 = new File(file,"demo.txt");
		if(!f1.exists()) {
			/*如果不存在,我们创建*/
			System.out.println("不存在");
			f1.createNewFile();
		}else {
			System.out.println("存在");
		}
		/*File(String parent,String child)*/
		File f2 = new File(".","d3");
		if(f2.exists()) {
			System.out.println("存在");
			System.out.println("绝对路径:"+f2.getAbsolutePath());
		}else {
			System.out.println("不存在");
			f2.mkdir();
		}
		
		File f3 = new File("."+File.separator+"d4"+File.separator+"x1");
		if(!f3.exists()) {
			f3.mkdirs();
		}
	}

       递归:
              递归思想:分成递与归。一层层递进,最后再一层层归。
              两种递归:
                     (1) 方法调用自己   
                     (2)  方法A调用方法B,方法B调用A
  练习代码

    /**
	 *  计算n的阶乘
	 * @param n
	 * @return
	 */
	public static long jieCheng(int n) {
		if(n==0||n==1) {
			return 1;
		}
		if(n<0) {
			throw new RuntimeException("不能传入负数");
		}
		long  result = n*jieCheng(n-1);
		return result;
    }

IO流(Input,Output)

       我们在做项目时,除了自定义的一些数据外,还可能需要从"外界"引入数据,或者将数据导出到"外界"。这时,我们需要I/O操作。
               外界:指的可能是  键盘,显示器,硬盘,或另外一个程序。
               输入:又叫读入操作,数据时从"外界"流向程序
               输出:又叫写出操作,数据时从程序流向"外界"

               流: 就是数据序列, 创建成功后,会打开一个通道。所以在使用完流后,应该进行关闭操作。
       IO流的分类:
               (1)按照流向分类:输入流输出流
               (2)按照处理的数据单位分类:字节流字符流
               (3)按照功能分类:
                        节点流:直接连接两个设备的流类型
                        处理流:对节点流再次封装与处理的流类型
 


字节流

       抽象父类 InputStream  /  OutputStream
       文件字节流:FileInputStream / FileOutputStream

 

  字节输入流:FileInputStream

               构造器:
                       FileInputStream(File file)    创建一个指定路径的File对象的文件输入流对象
                       FileInputStream(String name)    创建一个指定路径的字符串的文件输入流对象
                   常用方法:
                       int read()    读取该流中的一个字节数据,即8位二进制,存储到一个int数据的低八位上,如果返回-1,读至文件末尾,
                       long skip(long n)    跳过流中n个字节
                       int read(byte[] b)    读取字节存入byte数组中,最多能读b.length个字节,返回的是实际读取的字节个数
                       int available()    查看此输入流中剩余的字节数量

public static void main(String[] args) {
		FileInputStream fis = null;
		try {
			File file = new File("d4"+File.separator+"x1"+File.separator+"demo01.txt");
			//创建一个文件输入流对象
			fis  = new FileInputStream(file);
			//读取一个字节
			int b1 = fis.read();
			System.out.println((char)b1);
			int b2 = fis.read();
			System.out.println((char)b2);
			/*读取文件里的第5个字节*/
			fis.skip(2);
			int b3 = fis.read();
			System.out.println((char)b3);
			
			/*想一次性读取5个字节*/
			byte[] bs = new byte[5];
			int length = fis.read(bs);
			System.out.println("length:"+length);
			//解码:
			String info = new String(bs);
			System.out.println(info);
			
			/*查看剩余字节数量*/
			int leng = fis.available();
			System.out.println("leng:"+leng);
			fis.skip(-10);
			System.out.println(fis.available());			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

  字节输出流:FileOutputStream

               构造器:
                       FileOutputStream(File file)    创建文件输出流,输出到一个指定路径的File对象的文件
                       FileOutputStream(File file, boolean append)    创建文件输出流,输出到一个指定路径的File对象的文件,再次执行时,是否在文件末尾进行追加
                       FileOutputStream(String name)    创建文件输出流,输出到一个指定路径的文件
                       FileOutputStream(String name, boolean append)    创建一个指定路径的输出流对象,append表示在文件末尾追加
                       PS:如果指定路径下的文件名不存在,会自动创建。如果父路径不存在,则报异常FileNotFoundException
                   常用方法:
                       void write(int b)    写出参数b中的一个字节,int类型的低八位。
                       void write(byte[] b)    将字节数组b中的字节按顺序写出
                       void write(byte[] b,int off,int len)    将字节数组b中的字节按顺序写出,从下标off,写len个  

public static void main(String[] args) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream("d4\\x1\\demo01.txt");
			int num = 1026;// 00000100 00000010
			fos.write(num);//写的是1026的低八位
			String str = "你好,世界";
			byte[] bs = str.getBytes();
			fos.write(bs);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

  


缓冲流
   

  字节缓冲输出流:BufferedOutputStream

               在写数据时,如果一个字节一个字节的写,写的次数变得很多,效率就会变得很低。如何提高效率呢,这里我们就需要用到缓冲流了。
               缓冲输出流的特点:在流里维护了一个缓冲区,写字节时,先将字节写入缓冲区,当缓冲区满时,再一次性的将数据写到文件里。这样就降低了写的次数,因此提高了效率。因为写入次数的降低,缺失即时性,可以使用flush方法进行冲刷
    
               常用构造器:
                       BufferedOutputStream(OutputStream out)    创建一个指定字节输出流的缓冲流对象
                       BufferedOutputStream(OutputStream out,int size)    创建一个指定字节输出流的缓冲流对象,并设置缓冲区的大小
                       PS:当一次写的字节超出缓冲区大小,会不使用缓冲区,直接写入外部设备,效率变慢
         
               常用方法:
                       void write(int b)    将int数据的低八位,写入缓冲区内
                       void write(byte[] b,int off,int len)    将一段指定范围的字节数组,写入缓冲区  

public static void main(String[] args) {
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
				
		try {
			fos = new FileOutputStream("demo01.txt");
			/* 对文件输出流进行封装处理,
			 * 内部维护了一个缓冲区,即字节数组
			 * */
			bos = new BufferedOutputStream(fos);
			bos.write(10);//将10的一个字节,写入缓冲区
			bos.flush();//当缓冲区没有装满字节,不会自动冲刷,需要是手动,完成即时效果
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				/*
				 * 关闭前,一定会先执行flush方法,将
				 * 缓冲区的数据冲刷除去。
				 * 
				 * 如果是多个流的情况下,先关闭高级流,
				 * 再关闭低级流
				 * */
				bos.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

  字节缓冲输入流:BufferedInputStream

               在读取字节时,也是一个字节一个字节的读,次数多的话,效率就会降低。使用缓冲输入流,内部维护了一个缓冲区,默认大小8k,先一次性将缓冲区装满等待读取,当将缓冲区的数据读完后,缓冲区再次存储后续数据。读取的次数就会明显降低,效率也会提高      
     
               常用构造器:
                       BufferedInputStream(InputStream is)    创建一个指定字节输入流的缓冲流对象
                       BufferedInputStream(InputStream is,int size)    创建一个指定字节输入流的缓冲流对象,并设置缓冲区的大小
               常用方法:
                       int read(byte[] bs)    读取缓冲区里的字节,存储到bs中,当一次性读取的字节小于缓冲区,我们是从缓冲区里读数据。此时,效率很高,当一次性读取的字节超出缓冲区大小。将不使用缓冲区,会直接从文件里读。
                       int read(byte[] bs,int off,int len)    读取指定范围的字节    

public static void main(String[] args) {
		BufferedInputStream bis= null;
		try {
			bis = new BufferedInputStream(
					new FileInputStream("D:\\v1.mp4"));
			byte[] bs = new byte[1024];
			int length =-1;
			long time1 = System.currentTimeMillis();
			while((length=bis.read(bs))>0) {
			
			}
			long time2 = System.currentTimeMillis();
			System.out.println("时间:"+(time2-time1));
			
		} catch (Exception e) {
			
		}
	}

数据字节流

       与缓冲流一样,父类都是过滤字节流(FilterOutputStream/FilterInputStream)这两个类提供了几个特殊的方法,可以直接写基本数据类型

 

  数据输出流:DataOutputStream

               常用构造器
                       DataOutputStream(OutputStream os)    创建一个指定字节输出流的数据输出流对象
               常用方法:
                       除了提供写一个字节和写一个字节数组的方法外,还提供了如下方法      
                       void writeByte(int b)    将b的低八位写入
                       void writeShort(int s)    将b的低十六位写入
                       void writeInt(int i)    将int值写入
                       void writeLong(long l)    将long值写入
                       void writeFloat(float f)    将float值写入
                       void writeDouble(double d)    将double值写入
                       void writeChar(int c)    将char值写入
                       void writeBoolean(boolean b)    将boolean值写入
                       void writeUTF(String s)     使用UTF-8的编码方式将字符串传入

public static void main(String[] args) {
		DataOutputStream dos = null;
		try {
			dos = new DataOutputStream(
					new FileOutputStream("data.txt",true));
			/*写一个字节 'A' */
			dos.write('A');// 方法签名:write + int

			/*写一个byte类型的数据*/
			byte d1 = 65;
			dos.writeByte(d1);

			/*写一个Short类型的数据*/
			short d2 = 20013;
			dos.writeShort(d2);//写了2个字节

			/*写一个int类型的数据*/
			int num = 10;
			dos.writeInt(num);//写了4个字节

			/*写一个float类型的数据*/
			float d3 = 3.14f;
			dos.writeFloat(d3);//写了4个字节

			/*写一个double类型的数据*/
			double d4 = 3.14;
			dos.writeDouble(d4);//写了8个字节

			/*写一个long类型的数据*/
			long d5 = 1000;
			dos.writeLong(d5);//写了8个字节

			/*写一个char类型的数据*/
			char ch = '国';
			dos.writeChar(ch);//写了2个字节

			/*写一个boolean类型的数据*/
			boolean f = true;
			dos.writeBoolean(f);//写了一个字节
			
			String str = "我爱你们";
			dos.writeBytes(str);//写了4个字节
			
			String str1 = "你们爱我吗";
			dos.writeUTF(str1);

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				dos.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

  数据输入流:DataInputStream 

               常用构造器:
                       DataInputStream(InputStream in)     创建一个指定字节输入流的数据输入流对象
               常用方法:
                       byte readByte()         
                       short readShort() 
                       int readInt() 
                       long readLong() 
                       float readFloat() 
                       double readDouble()
                       char readChar()
                       boolean readBoolean()
                       String readUTF() 

public static void main(String[] args) {
		DataInputStream dis = null;
		try {
			dis = new DataInputStream(
					new FileInputStream("data.txt"));
			int d1 = dis.read();
			System.out.println((char)d1);
			byte d2 = dis.readByte();
			System.out.println(d2);
			short d3 = dis.readShort();
			System.out.println(d3);
			int d4 = dis.readInt();
			System.out.println(d4);
			float d5 = dis.readFloat();
			System.out.println(d5);
			double d6 = dis.readDouble();
			System.out.println(d6);
			long d7 = dis.readLong();
			System.out.println(d7);
			boolean f = dis.readBoolean();
			System.out.println(f);
			
//			byte[] b = new byte[4];
			System.out.println(dis.available());
			byte[] bs = new byte[1024];
			int length = dis.read(bs);
			System.out.println(new String(bs,0,length,"utf-8"));
		
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				dis.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

 

练习:使用缓冲字节流完成文件的复制

public static void main(String[] args) throws Exception {
		/*使用缓冲字节流完成文件的复制*/
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(
					new FileInputStream("D:/v1.mp4"));
			bos = new BufferedOutputStream(
					new FileOutputStream("D:/v2.mp4"));
			int length = -1;
			byte[] bs = new byte[4096];
			while((length=bis.read(bs))>0) {
				bos.write(bs,0,length);
			}
			bos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				bis.close();
				bos.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

 


对象流

       有的时候,我们可能需要将内存中的对象持久化到硬盘上,或者将硬盘中的对象信息读到内存中,这个时候我们需要使用对象输入输出流。
    
       序列化: 是将对象转换成一个字节序列的过程,是一个写操作
       反序列化:   一个字节序列转换成对象的过程 ,是一个读操作

 

  对象输出流:ObjectOutputStream

               构造器:
                       ObjectOutputStream(OutputStream out)     创建一个指定字节输出流的对象输出流对象。
          
               常用方法: 除了提供了一些基本数据类型的写方法外,还提供了
                       void writeObject(Object obj)    将内存中的对象持久化到硬盘上 

public static void main(String[] args) {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(
					new FileOutputStream("D:/object3.txt"));
			Person p = new Person();
			p.setName("张三");
			p.setAge(23);
			p.setGender('m');
			p.setBirth(new Date());
			p.setSalary(2000);
			p.setHobby(new String[] {"book","movie","music"});
			
			oos.writeObject(p);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				oos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
/*======================================================*/

public class Person implements Serializable{	
	private static final long serialVersionUID=1l;
	private String name;
	private int age;
	private char gender;
	private Date birth;
	private transient double salary;
	private String[] hobby;
	
	private boolean isMarry;
	
	public Person() {}

	public Person(String name, int age, char gender, Date birth, double salary, String[] hobby) {
		super();
		this.name = name;
		this.age = age;
		this.gender = gender;
		this.birth = birth;
		this.salary = salary;
		this.hobby = hobby;
	}
}


                    

  对象输入流:ObjectIntputStream 

               构造器:
                       ObjectIntputStream(OutputStream out)    创建一个指定字节输入流的对象输入流对象。
          
               常用方法: 除了提供了一些基本数据类型的读方法外,还提供了
                       Object readObject()    从硬盘上读取一个字节序列,转换成对象

public static void main(String[] args) {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(
					new FileInputStream("D:/object3.txt"));
			Person p = (Person)ois.readObject();
			System.out.println(p);
			System.out.println(p.isMarry());
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				ois.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

  序列化接口:Serializable


                       如果想将对象序列化,那么对象的类型必须实现此接口。此接口内什么都没有,只是一个序列化标识

                       serialVersionUID:每个能序列化的对象,在被序列化时,系统会默认给此对象的类计算一个序列化版本号。不同的平台默认提供的序列化版本号多数情况下不会相同。因此当我们反序列时,如果硬盘里存储的对象的版本号与当前设计的类型的版本号不一致。会出现运行时异常:java.io.InvalidClassException,这种情况叫不兼容问题。如果我们想解决不兼容问题。我们应该手动提供版本号。尽可能的相同这样来解决不兼容问题
      
                       另外一种情况:序列化过后,可能会修改类型,如果使用系统默认提供的版本号,在反序列时,会有异常,如果手动提供,则不会出现异常,多出来的成员变量,以默认值的形式,赋值给反序列化回来的对象【也就是在对一个对象进行序列化后,又在类中添加了其他成员变量,在没有重新序列化前,对其进行反序列化,此时输出后添加的成员变量的值为默认值】。

                       transient:成员变量的一个修饰词,可以理解为瘦身。有的时候,在序列化对象时,我们不需要将对象的某些成员变量值持久化到硬盘上(因为不重要),此时,我们可以在这些成员变量前添加修饰词transient(保存时,进行减肥)


字符流

       在输出输入操作时,以字符为单位进行操作,默认是unicode编码集,字符流的抽象父类分别是Writer/Reader,只能对纯文本文件进行操作

       已知直接子类: BufferedWriter  CharArrayWriter FilterWriter OutputStreamWriter PipedWriter PrintWriter StringWriter ,可以使用父类型的引用指向子类型。

  字符输出流:Writer 

               常用方法:
                       void close()    关闭 
                       void write(char[] cbuf)    写一个字符数组
                       void write(char[] cbuf, int off, int len)    写一个字符数组的一部分 
                       void write(int c)    写一个字符
                       void write(String str)    写一串字符
                       void write(String str, int off, int len)     写字符串的一部分 

  字符输入流:Reader

               常用方法:
                       int read()    读一个字符,存储到int的低16位
                       int read(char[] cbuf)    将数据读进字符数组中,返回的是读取的有效字符个数
                       int read(char[] cbuf, int off, int len)    将字符读入数组的一部分


缓冲流(数据)

 

  缓冲输出流:PrintWriter

               提供了丰富的方法,比BufferedWriter更加常用,此类型提供了行自动刷新的功能
               构造器:       
                       PrintWriter(File file) 
                       PrintWriter(OutputStream out)
                       PrintWriter(OutputStream out, boolean autoFlush)        
                       PrintWriter(String fileName) 
                       PrintWriter(Writer out) 
                       PrintWriter(Writer out, boolean autoFlush) 

                      上述构造器,有第二个参数的,可以设置为true,表示行自动刷新。  只有一个参数的构造器,相当有两个参数时,设置为false的情况,即取消了行自动刷新的功能
       
               常用方法:
                       void println()    通过写入行分隔符字符串来终止当前行。 
                       void println(boolean x)    打印一个布尔值,然后终止该行。  
                       void println(char x)    打印一个字符,然后终止该行。  
                       void println(char[] x)    打印字符数组,然后终止行。  
                       void println(double x)    打印双精度浮点数,然后终止行。  
                       void println(float x)    打印一个浮点数,然后终止该行。  
                       void println(int x)    打印一个整数,然后终止该行。  
                       void println(long x)    打印一个长整型,然后终止行。  
                       void println(Object x)    打印一个对象,然后终止该行。  
                       void println(String x)    打印字符串,然后终止行。

public static void main(String[] args) {
		PrintWriter pw = null;
		try {
			pw = new PrintWriter(
					new FileOutputStream("f1.txt"),true);
			pw.println(5);//
			pw.println("你是最帅的吗");
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			pw.close();
		}
	}

  缓冲输入流:BufferedReader

               提供了一个缓冲区
               构造器:   
                       BufferedReader(Reader in)    创建使用默认大小的输入缓冲区的缓冲字符输入流。  
                       BufferedReader(Reader in, int sz)    创建使用指定大小的输入缓冲区的缓冲字符输入流。
               常用方法:  
                       String readLine()    读一行字符串,读至换行符号为止,返回的数据不包含换行符,当返回值为null时,表示读至文件末尾

public static void main(String[] args) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(
					new InputStreamReader(
						new FileInputStream("f1.txt")));
			String line = br.readLine();
			System.out.println(line);
			line = br.readLine();
			System.out.println(line);
			line = br.readLine();
			System.out.println(line);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

转换流

  转换输出流:OutputStreamWriter

              将字符转换成字节写出到硬盘上
               构造器:          
                       OutputStreamWriter(OutputStream out)    创建一个指定字节输出流的字符输出流对象,采用的是系统默认的编码集 
                       OutputStreamWriter(OutputStream out, Charset cs) 
                       OutputStreamWriter(OutputStream out, CharsetEncoder enc) 
                       OutputStreamWriter(OutputStream out, String charsetName)
   创建一个指定字节输出流的字符输出流对象,采用指定编码集。 


               常用方法:     

                       void write(int a)    当a的低16位,如果被设计成相应的字符时,如果两个字节都是有效字节,会写出两个。如果低16位对应是无效字符,或是有效字节只有一位时,会写一个字节。      

public static void main(String[] args) {
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(
					new BufferedOutputStream(
							new FileOutputStream("demo01.txt",true),4096));
			/*写一个int类型的数据20013*/
			int num = 20013;
			osw.write(num);//写了两个字节
			/*写一个字符串"妈妈,我爱你"*/
			char[] ch = "妈妈,我爱你".toCharArray();
			osw.write(ch);
			String name = osw.getEncoding();
			System.out.println(name);
			/*写一个 "hellokitty"*/
			osw.write("hellokitty");
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				osw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


  转换输入流:InputStreamReader

              将字节转换成字符读进程序中
               构造器:
                       InputStreamReader(InputStream in)    创建一个使用默认字符集的InputStreamReader。  
                       InputStreamReader(InputStream in, Charset cs)    创建一个使用默认字符集的InputStreamReader,指定字符集
                       InputStreamReader(InputStream in, CharsetDecoder dec)    创建一个使用给定字符集解码器的InputStreamReader
                       InputStreamReader(InputStream in, String charsetName)    创建一个使用指定字符集的InputStreamReader。  

public static void main(String[] args) {
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(
					new BufferedInputStream(
						new FileInputStream("demo01.txt"),
						4096)
					,"GBK");
		int num =isr.read();
		System.out.println(num);

		char[] chs = new char[1024];
		int length = isr.read(chs);
		System.out.println(chs);
		
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

文件字符流

       FileWriter/FileReader
   

  文件字符输出流:FileWriter       

               相当于OutputStreamWriterFileOutputStream合起来的功能,内部也维护了一个缓冲区,但是需要手动flush
               构造器:
                       FileWriter(File file)    给一个File对象构造一个FileWriter对象。
                       FileWriter(File file, boolean append)    append:表示追加,但是此流不能设置字符集。
                       FileWriter(String fileName)    构造一个给定文件名的FileWriter对象
                       FileWriter(String fileName, boolean append)    构造一个FileWriter对象,给出一个带有布尔值的文件名,表示是否附加写入的数据
                       常用方法与 OutputStreamWriter的差不多
           

public static void main(String[] args) {
		FileWriter fw = null;
		try {
			fw = new FileWriter("f2.txt",true);
			fw.write("我是世界上最可爱的人");
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

  文件字符输入流:FileReader

               相当于InputStreamReader和FileInputStream合起来的功能内部也维护了一个缓冲区
               构造器:
                       FileReader(File file)    创建一个新的 FileReader ,给出 File路径
                       FileReader(String fileName)     创建一个新的 FileReader ,给出路径名
               常用方法与InputStreamReader的方法差不多

public static void main(String[] args) {
		FileReader fr = null;
		try {
			fr = new FileReader(new File("f2.txt"));
			char[] chs = new char[1024];
			int length = fr.read(chs);
			String str = new String(chs,0,length);
			System.out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值