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