我有一个Java程序可以在可移动驱动器中制作文件的副本。但问题是用户必须输入驱动器号和文件夹(G:\ Folder \ File)才能让程序读取要复制的文件。如果他们没有指定,那么程序将从工作空间目录中读取,因此任何指定但在工作空间目录中不存在的文件都将导致错误消息。是否可以将目录更改为检测到的可移动驱动器的驱动器号而不是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();
}
}
}
程序将提示用户输入文件名(包括驱动器号)。例如,在"要复制的文件:",用户必须输入G:\ Folder \ File而不仅仅是Folder \ File或只是文件,程序才能找到该文件到复制。我希望将目录设置为可移动驱动器的驱动器号。有没有办法这样做?
答案 0 :(得分:0)
您可以使用File.listRoots()
列出系统中的所有驱动器。并要求用户选择。
但很难知道哪一个是可移动驱动器。您可能仍需要让用户选择是否有多个可移动驱动器。