zoukankan      html  css  js  c++  java
  • 黑马程序员——java基础之文件复制

    ---------------------- ASP.Net+Unity开发.Net培训、期待与您交流!----------------------  

     

     <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流!

    文件复制的两种方法。这里主要讲解的是第一种该注意的地方。

    注意,在用单个字符即取即存的时候,ch=fr.read() ,ch就是等于读取到的字符的ASCII对应的整型数据。在写入的时候,fw.write(ch) 。write( int ch).传入的是整型,写入后,自动转成char型。而在使用数组的时候,len = fr.read(buf)),len则等于读取到的字符数组的长度,字符仍缓存在字符数组buf中。字符都是通过flush或者close刷入文件中的。

    import java.io.*;
    /*
       文件复制原理:
       将C盘文件下的数据存储到D盘的一个文件下
    
       步骤:
       1.在D盘下创建一个文件,来存储C盘文件中的数据
       2.定义读取流和C盘文件关联
       3.通过不断的读写完成数据存储
       4.关闭数据流
    */
    
    class CopyText
    {
    	public static void main(String[] args) throws IOException
    	{
    	    copy_1();
    		
    	}
    
    	public static void copy_2()
    	{
            FileWriter fw = null ;
    		FileReader fr = null ;
    		try
    		{
    			fw = new FileWriter("demo.txt");
    			fr = new FileReader("1.txt");
    
    			char[] ch = new char[1024];
    			int len = 0;
    			while ((len = fr.read(buf))!=-1)
    			{
    				fw.write(buf,0,len);
    			}
    
    		}
    		catch (IOException e)
    		{
    			throw new RuntimeException("读写失败");
    
    		}
    		finally
    		{
    			if(fr!=null)
    				try
    				{
    					fr.close();
    				}
    				catch (IOException e)
    				{ 
    					
    				}
    			if(fw!=null)
    				try
    				{
    					fw.close();
    				}
    				catch (IOException e)
    				{
    				}
    		
    		}
    	
    	}
    	
    
         //从C盘读取一个字符,就往D盘写入一个字符
         public static void copy_1() throws IOException
    	{
    		//创建目的地
            FileWriter fw = new FileWriter("1.txt");
    		//与已有文件关联
    		FileReader fr = new FileReader("demo.txt");
    
    		int ch = 0;
    
    		while ((ch=fr.read())!=-1)
    		{
    			fw.write(ch);
    			System.out.println((char)ch);
    			
    		}
    		System.out.println(ch);
    		fw.close();
    		fr.close();
    
    	}
    
    }
    


     

    ---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------

  • 相关阅读:
    hdu 1028 Ignatius and the Princess III (n的划分)
    CodeForces
    poj 3254 Corn Fields (状压DP入门)
    HYSBZ 1040 骑士 (基环外向树DP)
    PAT 1071 Speech Patterns (25)
    PAT 1077 Kuchiguse (20)
    PAT 1043 Is It a Binary Search Tree (25)
    PAT 1053 Path of Equal Weight (30)
    c++ 常用标准库
    常见数学问题
  • 原文地址:https://www.cnblogs.com/shoneworn/p/5078121.html
Copyright © 2011-2022 走看看