移动文件有一种简单方法,不需要复制文件再删除文件。
package com.unir.test01; import java.io.File; import java.io.IOException; public class Test02 { public static void main(String[] args) throws IOException { //创建文件 File f=new File("d:\developer\6.txt"); f.renameTo(new File("E:\英雄时刻"));//移动到e盘 f.delete();//删除 } }
使用FileInputStream类的read(byte[])方法和FileOutputStream类的write(byte[])方法实现文件移动。
已知文件:d:\developer\56.txt
目标地址:e:\英雄时刻\56.txt
package com.unir.test01; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Test01 { /* 已知文件:d:/developer/12345.txt 目标地址:e:/英雄时刻/12345.txt */ public static void main(String[] args) throws IOException { //创建文件 File f=new File("d:\developer\12345.txt"); //创建字符 String txt="nice."; byte[] b=txt.getBytes(); FileOutputStream fos=new FileOutputStream(f); fos.write(b); //创建输入流 FileInputStream input = new FileInputStream("d:/developer/12345.txt"); //创建输出流 FileOutputStream output = new FileOutputStream("e:/英雄时刻/12345.txt"); int len = 0; byte[] buf = new byte[1024]; if((len = input.read(buf)) > -1){ output.write(buf, 0 , len); } fos.close(); input.close(); output.close(); f.delete(); } }
使用BufferedInputStream类的read方法和BufferedOutputStream类的write方法实现文件移动。
已知文件:d:\developer\56.txt
目标地址:e:\英雄时刻\56.txt
package com.unir.test01; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; public class Test04 { public static void main(String[] args) throws IOException { FileInputStream f=new FileInputStream("D:\developer\9.txt"); InputStreamReader i=new InputStreamReader(f,"utf-8"); FileOutputStream f1=new FileOutputStream("e:\英雄时刻\9.txt",true); BufferedOutputStream b=new BufferedOutputStream(f1); int len = 0; byte[] buf = new byte[1024]; if((len = i.read()) != -1){ b.write(buf, 0 , len); } b.close(); i.close(); File file=new File("D:\developer\9.txt"); file.delete(); } }
从键盘读入“Java IO流的分类”,并将这些文字写入文件d:\developer\9.txt,然后将该文件复制到e:\英雄时刻\9.txt
package com.unir.test01; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; public class Test04 { public static void main(String[] args) throws IOException { FileInputStream f=new FileInputStream("D:\developer\9.txt"); InputStreamReader i=new InputStreamReader(f,"utf-8"); FileOutputStream f1=new FileOutputStream("e:\英雄时刻\9.txt",true); BufferedOutputStream b=new BufferedOutputStream(f1); int len = 0; byte[] buf = new byte[1024]; if((len = i.read()) != -1){ b.write(buf, 0 , len); } b.close(); i.close(); File file=new File("D:\developer\9.txt"); file.delete(); } }
中。