当前位置: 代码迷 >> Eclipse >> java中对文件如何重命名
  详细解决方案

java中对文件如何重命名

热度:6   发布时间:2016-04-23 01:16:20.0
java中对文件怎么重命名
我先创建一个a.txt文件,然后在把a.txt删除之前,copy给了b.txt,,再删除a.txt之后,,又想把b.txt改名成a.txt。。我用renameto()..实现不了。。求给我帮助一下。。

package ys.TestDemo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

public class TestFiles {
     public static void main(String[] args) {
     File file=new File("d:aa//bb//c.txt");
     file.getParentFile().mkdirs();
     try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}

try {
PrintStream ps=new PrintStream(file);
ps.println("你在干嘛");
ps.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String s=file.getAbsolutePath();
        System.out.println("ssss"+s);
File file1=new File("d:aa//bb//b.txt");
if(file.exists()){
Copy( file, file1);
    file.deleteOnExit();
}
File file2=new File(s);
file1.renameTo(file2);

System.out.println("......"+file1.getAbsolutePath());

}

     private static void Copy(File file, File file2) {
     try {
     BufferedReader  buf=
     new BufferedReader(
     new InputStreamReader(
     new FileInputStream(file)));
    
       //BufferedReader和Ps连用(70%)
       PrintStream  ps=new PrintStream(file2);
       String  str=null;
       while((str=buf.readLine())!=null){
             ps.println(str);   
       }
       ps.close();
       buf.close();
       } catch (FileNotFoundException e) {
     e.printStackTrace();
     } catch (IOException e) {
     e.printStackTrace();
     } 
     }
  相关解决方案