Java 如何写入USB(外部存储器)
我正在尝试用java将一个文件从我的计算机复制到USB。问题是,代码在Usb上创建了一个文件,但文件的内容没有从源复制到目标(计算机到Usb)。我该怎么做? 我希望将文件名R.java作为system.txt复制到usb中Java 如何写入USB(外部存储器),java,file,usb,Java,File,Usb,我正在尝试用java将一个文件从我的计算机复制到USB。问题是,代码在Usb上创建了一个文件,但文件的内容没有从源复制到目标(计算机到Usb)。我该怎么做? 我希望将文件名R.java作为system.txt复制到usb中 import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class R {
private static File to;
public static void main(String[] args) {
// current working dir where there is file u want to replicate
File f = new File("." + "/R.java");
// destination location
File so = new File("/media");
for (File s : so.listFiles()) {
String r = s.getName();
to = new File("/media/" + r + "/system.txt");
if (!to.exists()) {
try {
to.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out
.print(to.getName() + " " + e.getMessage() + "\n");
}
}
if (f.exists()) {
FileChannel is = null;
FileChannel os = null;
try {
is = new FileInputStream(f).getChannel();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
os = new FileOutputStream(to).getChannel();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
os.transferFrom(is, 0, is.size());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
我在LINUX机器上我想如果你正确地缩进代码(你的IDE有一个“格式”选项),你就会看到问题:只有当
to
文件已经存在时,才会进行复制,因为它在else
块中。即使我删除了else块,它也不起作用。我试图添加其他可能是我可以工作,但它不工作您的从
传输部分不正确,那么。但请使用最新的来源更新您的问题(例如,不使用else
,并使用适当的缩进)。ooooooooooooooooooooh现在正在运行,谢谢您……。好的。。。我只想补充一点,如果您使用,您可以为自己保存大量代码。我认为如果您正确缩进代码(您的IDE有一个“格式”选项),您就会看到问题:只有当到文件已经存在时,才会进行复制,因为它位于else
块内。即使删除else块,它也无法工作。我试图添加其他可能是我可以工作,但它不工作您的从
传输部分不正确,那么。但请使用最新的来源更新您的问题(例如,不使用else
,并使用适当的缩进)。ooooooooooooooooooooh现在正在运行,谢谢您……。好的。。。我只想补充一点,如果您使用。