-------android培训、java培训、期待与您交流! ----------
⊙代码练习
public class FileCopy
{
/**
* //将C盘一个文本文件复制到D盘。
/*
复制的原理:
其实就是将C盘下的文件数据存储到D盘的一个文件中。
步骤:
1,在D盘创建一个文件。用于存储C盘文件中的数据。
2,定义读取流和C盘文件关联。
3,通过不断的读写完成数据存储。
4,关闭资源。
*/
public static void main(String[] args)
{
//逐个字符拷贝
copy_1();
//按字符数组拷贝
copty_2();
}
private static void copty_2()
{
FileReader fr = null;
FileWriter fw = null;
try
{
fr = new FileReader("whbTest.txt");
fw = new FileWriter("whbTest_copy2.txt");
char[] buff = new char[1024];
int len = 0;
while(-1 != (len=fr.read(buff)))
{
fw.write(buff, 0, len);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if(fr != null)
try
{
fr.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
fw.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private static void copy_1()
{
FileReader fr = null;
FileWriter fw = null;
try
{
fr = new FileReader("whbTest.txt");
fw = new FileWriter("whbTest_copy.txt");
int c; //逐个字符拷贝
while(-1 != (c=fr.read()))
{
fw.write(c);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if(fr != null)
try
{
fr.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if(fw != null) try
{
fw.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}