• java_25 FileReader类和FileWriter类


    1.FileWriter

      1.1FileWriter 用于写入字符流。要写入原始字节流,请考虑使用 FileOutputStream

    public class Demo {
    	public static void main(String[] args) throws IOException{
    		FileWriter fileWriter = new FileWriter("d:\aaa.txt");
    		//添加字符
    		fileWriter.write(100);
    		fileWriter.write(101);
    		//添加字符数组
    		char[] c = {'a','b','c','d'};
    		fileWriter.write(c);
    		fileWriter.write(c,1,2);
    		//添加字符串
    		fileWriter.write("hello world");
    		fileWriter.flush();
    		fileWriter.close();
    	}
    }
    

    2.FileReader

      1.1用来读取字符文件的便捷类。FileReader 用于读取字符流。要读取原始字节流,请考虑使用 FileInputStream

      //flush  和close区别
           // flush用来刷新缓冲区的  只有字符流才需要刷新  

      字节读取

    public class Demo {
    	public static void main(String[] args) throws IOException{
    		FileReader fileReader = new FileReader("d:\aaa.txt");
    		int len = 0;
    		while((len=fileReader.read())!=-1) {
    			System.out.print((char)len);
    		}
    		fileReader.close();
    	}
    }
    

       字符数组读取

    public class Demo {
    	public static void main(String[] args) throws IOException{
    		FileReader fileReader = new FileReader("d:\aaa.txt");
    		char[] b = new char[1024];
    		int len = 0;
    		while((len = fileReader.read(b))!=-1) {
    			System.out.println(new String(b,0,len));
    		}
    		fileReader.close();
    	}
    }
    

    3.传输数据

      

    public class Demo {
    	public static void main(String[] args){
    		FileReader fileReader = null;
    		FileWriter fileWriter = null;
    		try {
    			fileReader = new FileReader("d:\aaa.txt");
    			fileWriter = new FileWriter("d:\bbb/txt");
    			char[] ch = new char[1024];
    			int len = 0;
    			while((len=fileReader.read(ch))!=-1) {
    				fileWriter.write(ch,0,len);
    				fileWriter.flush();
    			}
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}finally {
    			if(fileWriter!=null) {
    				try {
    					fileWriter.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    			if(fileReader!=null) {
    				try {
    					fileReader.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    }
    
  • 相关阅读:
    模块(module)
    编译和解释性语言和python运行方式
    管道通信初级
    Page.TryUpdateModel 方法
    运用模型绑定和web窗体显示和检索数据(Retrieving and displaying data with model binding and web forms)
    HttpResponse 类
    ASP.NET中IsPostBack详解
    3.4.1 使用过滤式扩展方法(P43-44)
    使用扩展方法(Chapter3 P39-41)
    C#对象初始或器-Chapter3 P38
  • 原文地址:https://www.cnblogs.com/smxbo/p/10698523.html
Copyright © 2020-2023  润新知