JavaIO 复制文件到任意路径,支持目标文件父路径不存在的情况

来看一个例子:

package command.line.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestFilePath
{
    public static void main(String[] args)
    {
        // 源文件:
        // D:\dev\workspace\CmdShellTools\蓝精灵1.jpg
        File fromFile = new File("D:\\dev\\workspace\\CmdShellTools\\蓝精灵1.jpg");
        File toFile = new File(
                "D:\\dev\\workspace\\CmdShellTools\\new1\\new2\\蓝精灵2.jpg");
         copyByStream(fromFile,toFile);
    }
    /**
     * @param fromFile
     * @param toFile
     */
    public static void copyByStream(File fromFile, File toFile)
    {
        FileInputStream ins = null;
        FileOutputStream out = null;
        try
        {
            ins = new FileInputStream(fromFile);
            /*
             * 使用FileOutputStream写文件
             * 如果目标文件不存在,则FileOutputStream会创建目标文件(前提是父路径文件对象必须存在)。
             */
            out = new FileOutputStream(toFile);
            byte[] buf = new byte[1024];
            int size = 0;
            // 每次读取1024个字节,然后写入1024自己
            while ((size = ins.read(buf)) != -1)
            {
                out.write(buf, 0, size);
            }

        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally
        {
            if (ins != null)
            {
                try
                {
                    ins.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (out != null)
            {
                try
                {
                    out.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

        }
    }// 方法结束
}

当前的工程目录如下:
这里写图片描述
现在我要拷贝工程目下的蓝精灵1.jpg(路径为:D:\dev\workspace\CmdShellTools\蓝精灵1.jpg)到当然工程路径下的new1\new2\蓝精灵2.jpg。但是呢,从上面的图中可以看出,.\new1\new2这个路径并不存在。这个时候因为目标文件不在当前路径下,FileOutputStream就不会创建这个文件,这样就会导致FileNotFoundException异常:
运行上面的代码,输出结果为:

java.io.FileNotFoundException: D:\dev\workspace\CmdShellTools\new1\new2\蓝精灵1.jpg (系统找不到指定的路径。)
......
    at command.line.test.TestFilePath.main(TestFilePath.java:37)

那我先创建这个文件不就行了吗?使用toFile.createNewFile()创建该文件。把上面的main方法改成:

    public static void main(String[] args)
    {
        // 源文件:
        // D:\dev\workspace\CmdShellTools\蓝精灵1.jpg
        File fromFile = new File("D:\\dev\\workspace\\CmdShellTools\\蓝精灵1.jpg");
        File toFile = new File(
                "D:\\dev\\workspace\\CmdShellTools\\new1\\new2\\蓝精灵2.jpg");
        if(!toFile.exists())
        {
            try
            {
                toFile.createNewFile();
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
         copyByStream(fromFile,toFile);
    }

运行结果:

java.io.IOException: 系统找不到指定的路径。
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(Unknown Source)
    at command.line.test.TestFilePath.main(TestFilePath.java:21)
java.io.FileNotFoundException: D:\dev\workspace\CmdShellTools\new1\new2\蓝精灵1.jpg (系统找不到指定的路径。)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at command.line.test.TestFilePath.copyByStream(TestFilePath.java:65)
    at command.line.test.TestFilePath.main(TestFilePath.java:48)

可以看到这样也是不行的,File类也不到这个不存在的路径。

解决方法:

先创建.\new1\new2这两个不存在的文件夹,然后再创建.\new1\new2\蓝精灵2.jpg。这样就可以了,具体代码如下:

    public static void main(String[] args)
    {
        // 源文件:
        // D:\dev\workspace\CmdShellTools\蓝精灵1.jpg
        File fromFile = new File("D:\\dev\\workspace\\CmdShellTools\\蓝精灵1.jpg");
        File toFile = new File(
                "D:\\dev\\workspace\\CmdShellTools\\new1\\new2\\蓝精灵2.jpg");
//      if(!toFile.exists())
//      {
//          try
//          {
//              toFile.createNewFile();
//          } catch (IOException e)
//          {
//              // TODO Auto-generated catch block
//              e.printStackTrace();
//          }
//      }
        //如果文件不存在
        if (!toFile.exists())
        {
            //先创建该文件的所有上级目录
            if (toFile.getParentFile().mkdirs())
            {
                try
                {
                    //再创建该文件
                    toFile.createNewFile();
                } catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
        // 因为不是在同一目录下,所以必须要先创建源文件,不然FileOutputStream找不到这个文件,将会复制失败
         copyByStream(fromFile,toFile);
    }

这样就可以了,运行结果:
这里写图片描述
可以看到现在已经在当前工程目录(D:\dev\workspace\CmdShellTools)下,新建了子目录new1\new2,而且复制文件也成功了。
这里个关键操作就是

if (!toFile.exists())
{
    //先创建该文件的所有上级目录
    if (toFile.getParentFile().mkdirs())
    {
        try
        {
            //再创建该文件
            toFile.createNewFile();
        } catch (IOException e)
        {
        }
    }
}

意思就是,如果这个系统中找不到新文件的路径,那应该是他的父目录没有建好,所以,先使用toFile.getParentFile()获取该文件的父路径的File对象,然后再创建使用mkdirs()方法创建这些父路径。如果父路径创建成功了,我们再创建这个文件。其实这个文件不用创建也是可以的,只要文件蓝精灵2.jpg的父目录存在,FileOutputStream就可以自动创建这个文件,所以把上面的代码改成下面的形式也是可以的。

//如果文件不存在
if (!toFile.exists())
{
    toFile.getParentFile().mkdirs();
}
// 因为不是在同一目录下,所以必须要先创建源文件,不然FileOutputStream找不到这个文件,将会复制失败
copyByStream(fromFile,toFile);

最终版本:

package command.line.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestFilePath
{
    public static void main(String[] args)
    {
        File fromFile = new File(".\\蓝精灵1.jpg");
        File toFile = new File(".\\new1\\new2\\蓝精灵2.jpg");
        if (fromFile.exists())
        {
            // 如果文件不存在
            if (!toFile.exists())
            {
                toFile.getParentFile().mkdirs();
            }
            // 因为不是在同一目录下,所以必须要先创建源文件,不然FileOutputStream找不到这个文件,将会复制失败
            copyByStream(fromFile, toFile);
        } else
        {
            System.out.println("源文件不存在");
        }
    }
    /**
     * @param fromFile
     * @param toFile
     */
    public static void copyByStream(File fromFile, File toFile)
    {
        FileInputStream ins = null;
        FileOutputStream out = null;
        try
        {
            ins = new FileInputStream(fromFile);
            /*
             * 使用FileOutputStream写文件
             * 如果目标文件不存在,则FileOutputStream会创建目标文件(前提是父路径文件对象必须存在)。
             */
            out = new FileOutputStream(toFile);
            byte[] buf = new byte[1024];
            int size = 0;
            // 每次读取1024个字节,然后写入1024自己
            while ((size = ins.read(buf)) != -1)
            {
                out.write(buf, 0, size);
            }

        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally
        {
            if (ins != null)
            {
                try
                {
                    ins.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (out != null)
            {
                try
                {
                    out.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

        }
    }// 方法结束
}

当然,可以把上面复制文件的代码整合到一个方法中

复制文件到任意路径的方法如下:

/**
 * @param fromFile
 * @param toFile
 */
public static void copyByStream(File fromFile, File toFile)
{
    //源文件存在才复制
    if (fromFile.exists())
    {
        // 如果找不到目标文件
        if (!toFile.exists())
        {
            //这说明目标文件的上级目录不存在,先新建所有的上级目录
            toFile.getParentFile().mkdirs();
        }
        FileInputStream ins = null;
        FileOutputStream out = null;
        try
        {
            ins = new FileInputStream(fromFile);
            /*
             * 使用FileOutputStream写文件
             * 如果目标文件不存在,则FileOutputStream会创建目标文件(前提是父路径文件对象必须存在)。
             */
            out = new FileOutputStream(toFile);
            byte[] buf = new byte[1024];
            int size = 0;
            // 每次读取1024个字节,然后写入1024自己
            while ((size = ins.read(buf)) != -1)
            {
                out.write(buf, 0, size);
            }

        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally
        {
            if (ins != null)
            {
                try
                {
                    ins.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (out != null)
            {
                try
                {
                    out.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

        }

    } else
    {
        System.out.println("源文件不存在");
    }
}

使用方式:

package command.line.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestFilePath
{
    public static void main(String[] args)
    {
        File fromFile = new File(".\\蓝精灵1.jpg");
        File toFile = new File(".\\new1\\new2\\蓝精灵2.jpg");
        copyByStream(fromFile, toFile);
    }
    /**
     * @param fromFile
     * @param toFile
     */
    public static void copyByStream(File fromFile, File toFile)
    {
        //源文件存在才复制
        if (fromFile.exists())
        {
            // 如果找不到目标文件
            if (!toFile.exists())
            {
                //这说明目标文件的上级目录不存在,先新建所有的上级目录
                toFile.getParentFile().mkdirs();
            }
            FileInputStream ins = null;
            FileOutputStream out = null;
            try
            {
                ins = new FileInputStream(fromFile);
                /*
                 * 使用FileOutputStream写文件
                 * 如果目标文件不存在,则FileOutputStream会创建目标文件(前提是父路径文件对象必须存在)。
                 */
                out = new FileOutputStream(toFile);
                byte[] buf = new byte[1024];
                int size = 0;
                // 每次读取1024个字节,然后写入1024自己
                while ((size = ins.read(buf)) != -1)
                {
                    out.write(buf, 0, size);
                }

            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally
            {
                if (ins != null)
                {
                    try
                    {
                        ins.close();
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
                if (out != null)
                {
                    try
                    {
                        out.close();
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }

            }

        } else
        {
            System.out.println("源文件不存在");
        }
    }
}
Java可以通过使用标准的Java IO API和网络编程API从服务器上下载文件。以下是一些基本步骤: 1. 创建一个URL对象,使用该对象表示服务器上的文件路径文件名。 2. 使用URLConnection打开连接并设置HTTP请求的相关属性(例如,使用GET请求方法)。 3. 使用URLConnection.getInputStream()方法获取输入流,这个流可以用于读取服务器上的文件内容。 4. 将输入流写入到程序中,可以使用Java IO API中的文件输出流或其他适当的输出流。 下面是一些示例代码,可以根据您的需要进行修改: ```java import java.io.*; import java.net.*; public class FileDownloader { public static void main(String[] args) { String serverFilePath = "http://example.com/path/to/file.jpg"; // 服务器文件路径 String localFilePath = "/path/to/local/file.jpg"; // 下载到本地的文件路径 try { URL url = new URL(serverFilePath); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(localFilePath); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们首先创建一个URL对象来表示服务器文件路径,然后打开URLConnection并获取输入流。接下来,我们使用Java IO API中的FileOutputStream将输入流写入到本地文件中。 请注意,如果服务器需要进行身份验证或使用HTTPS协议,您可能需要在打开URLConnection之前设置其他HTTP请求属性。具体的细节可能会因服务器的配置而有所不同。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值