黑马程序员技术交流社区
标题:
File和IO的小练习
[打印本页]
作者:
奋发吧小白
时间:
2014-11-5 11:35
标题:
File和IO的小练习
复制Mp3
package IO流练习;
import java.io.*;
public class 复制MP3 {
public static void main(String[] args)throws Exception {
copyMp3();
System.out.println("复制完成");
}
public static void copyMp3() throws Exception
{
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("D:\\1.mp3"));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("D:\\001.mp3"));
byte [] b = new byte[1024];
int len = 0;
while((len = bis.read(b))!=-1)
{
bos.write(b, 0, len);
bos.flush();
}
bos.close();
bis.close();
}
}
复制代码
复制图片
package IO流练习;
import java.io.*;
public class 复制图片 {
public static void main(String[] args)throws Exception {
copyPic();
System.out.println("复制完成!");
}
public static void copyPic() throws Exception
{
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("D:\\1.jpg"));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("D:\\001.jpg"));
byte [] b = new byte [1024];
int len = 0;
while((len = bis.read(b))!=-1)
{
bos.write(b, 0, len);
bos.flush();
}
bis.close();
bos.close();
}
}
复制代码
复制文件夹
package IO流练习;
import java.io.*;
public class 复制文件夹 {
public static void main(String[] args) throws Exception{
File srcDir = new File("D:\\heima");
File disDir = new File("D:\\Copy05heima");
if(!disDir.exists())
{
disDir.mkdirs();
}
copyFolder(srcDir,disDir);
System.out.println("复制成功");
}
public static void copyFolder(File srcDir,File disDir) throws Exception
{
File [] files = srcDir.listFiles();
for (File file : files) {
if(file.isDirectory())
{
File newDir = new File(disDir+File.separator+file.getName());
newDir.mkdirs();
copyFolder(file,newDir);
}else
{
File newFile = new File(disDir+File.separator+file.getName());
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte [] buf = new byte[1024];
int len = 0;
while((len = bis.read(buf))!=-1)
{
bos.write(buf, 0, len);
bos.flush();
}
bis.close();
bos.close();
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2