开发者

Writing files into a directory which still does not exists

I'm using this script on WINDOWS

public void copyFile(File sourceDirectory, File targetFile, File targetDirectory) throws IOException{
    String temp = targetFile.getAbsolutePath();
    String relativeD = temp.substring(sourceDirectory.getAbsolutePath().length(), targetFile.getAbsolutePath().length());
    String rootD = sourceDirectory.getName();
    String fullPath = targetDirectory.getAbsolutePath() + rootD + relativeD;
    File fP = new File( fullPath );
    System.out.println("PATH: " + fullPath);
    FileChannel inChannel = new FileInputStream(targetF开发者_JAVA技巧ile).getChannel();
    FileChannel outChannel = new FileOutputStream( fP ).getChannel();
    int maxCount = (64 * 1024 * 1024) - (32 * 1024);
    long size = inChannel.size();
    long position = 0;
    while (position < size) {
            position += inChannel.transferTo(position, maxCount, outChannel);
     }
    if (inChannel != null) inChannel.close();
    if (outChannel != null) outChannel.close();
}

What I'm doing is simple. I need to copy a file from a location to another but I have to keep the directories they're in.

So with relativeD I'm taking something like this: dir/files.sql or simply files.sql.

This is happening because for specific directories I need to copy them recursively respecting the tree structure.

The problem is this method is not working. I don't know why because if I use a simple

    FileChannel outChannel = new FileOutputStream( new File( targetDirectory, targetFile ) ).getChannel();

it works. I suppose this is happening because in this case it's copying the file under an existing directory.


According to this article (top Google search hit for 'java mkdir recursive'):

Have a look at the java.io.File : it does the job perfectly, with the mkdirs function :

    new File("c:/aaa/bbb/ccc/ddd").mkdirs();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜