简体   繁体   English

在Java中将目录设置为可移动驱动器目录

[英]Set directory to removable drive directory in Java

I have a Java program to make a copy of a file in a removable drive. 我有一个Java程序可以在可移动驱动器中复制文件。 But the problem is that the user will have to type in the drive letter and folder (G:\\Folder\\File) for the program to read the file to copy. 但是问题在于,用户将必须输入驱动器号和文件夹(G:\\ Folder \\ File),程序才能读取要复制的文件。 If they do not specify then the program will read from the workspace directory, therefore any file that is specified but does not exist in the workspace directory will cause an error message. 如果未指定,则程序将从工作区目录中读取,因此,指定但工作区目录中不存在的任何文件都将导致错误消息。 Is it possible to change the directory to the drive letter of a removable drive detected instead of the workspace in Java codes? 是否可以将目录更改为检测到的可移动驱动器的驱动器号,而不是Java代码中的工作区?

FileCopy.java FileCopy.java

public class FileCopy 
{   
    public static void main(String[] args)
    {

        Scanner userInput = new Scanner(System.in);

        InputStream inStream = null;
        OutputStream outStream = null;

        try
        {

            System.out.print("\nFile to copy: ");
            String filename = userInput.nextLine();
            System.out.print("\nNew filename: ");
            String newname = userInput.nextLine();

            File file1 = new File(filename);
            File file2 = new File(newname);

            inStream = new FileInputStream(file1);
            outStream = new FileOutputStream(file2);

            byte[] buffer = new byte[1024];

            int length;
            //copy the file content in bytes 
            while ((length = inStream.read(buffer)) > 0)
            {
                outStream.write(buffer, 0, length);
            }

            inStream.close();
            outStream.close();

            System.out.println("File is copied successful!");

        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

The program will prompt the user to type in the file name (including drive letter). 该程序将提示用户键入文件名(包括驱动器号)。 For example, at "File to copy: ", the user will have to type in G:\\Folder\\File instead of just Folder\\File or just File for the program to be able to find the file to copy. 例如,在“要复制的文件:”中,用户必须键入G:\\ Folder \\ File而不是Folder \\ File或仅输入File,程序才能找到要复制的文件。 I would like the directory to be set to whatever the drive letter of the removable drive is. 我希望将目录设置为可移动驱动器的驱动器号。 Is there any way to do so? 有什么办法吗?

You can use File.listRoots() to list all drives in the system. 您可以使用File.listRoots()列出系统中的所有驱动器。 And ask user to select. 并要求用户选择。

But it is hard to know which one is removable drive. 但是很难知道哪一个是可移动驱动器。 You may still need to ask user to select if there are multiple removable drives. 您可能仍然需要询问用户选择是否有多个可移动驱动器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM