Java IO 创建文件解决文件名重复问题

*转载地址:点击打开链接

文件名不存在不修改文件名,如果存在在文件名后面加数字,1,2,3


代码演示

package practice.IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * @author 言曌
 * @date 2017/12/2 上午10:59
 */
public class Demo {
    /**
     * 将 /Users/liuyanzhao/Desktop/spring.jpeg 文件
     * 拷贝到
     * /Users/liuyanzhao/Desktop/io/中
     * 需要避免文件名重复覆盖的情况
     */
    public static void main(String args[]) throws IOException {
        //源文件
        File sourceFile = new File("/Users/liuyanzhao/Desktop/spring.jpeg");
        //文件的完整名称,如spring.jpeg
        String filename = sourceFile.getName();
        //文件名,如spring
        String name = filename.substring(0,filename.indexOf("."));
        //文件后缀,如.jpeg
        String suffix = filename.substring(filename.lastIndexOf("."));
        //目标文件
        File descFile = new File("/Users/liuyanzhao/Desktop/io"+File.separator+filename);
        int i = 1;
        //若文件存在重命名
        while(descFile.exists()) {
            String newFilename = name+"("+i+")"+suffix;
            String parentPath = descFile.getParent();
            descFile = new File(parentPath+ File.separator+newFilename);
            i++;
        }
        descFile.createNewFile();  //新建文件
        FileInputStream fin = new FileInputStream(sourceFile);
        FileOutputStream fout = new FileOutputStream(descFile);
        byte[] data = new byte[512];
        int rs = -1;
        while((rs=fin.read(data))>0) {
            fout.write(data,0,rs);
        }
        fout.close();
        fin.close();
    }
}

猜你喜欢

转载自blog.csdn.net/shaohe18362202126/article/details/80717385
今日推荐