一直困扰我的是,用Java复制文件的唯一方法是打开流,声明一个缓冲区,读取一个文件,循环遍历它,然后将其写入另一个文件.Web上充斥着类似但仍然略有不同的此类解决方案的实现.
有没有更好的方法保持在Java语言的范围内(意味着不涉及执行特定于操作系统的命令)?也许在一些可靠的开源实用程序包中,这至少会掩盖这个底层实现并提供单行解决方案?
在Java Path-String中使用File.separator和普通/有什么区别?
与双反斜杠\\平台相比,独立性似乎不是原因,因为两个版本都可以在Windows和Unix下运行.
public class SlashTest {
@Test
public void slash() throws Exception {
File file = new File("src/trials/SlashTest.java");
assertThat(file.exists(), is(true));
}
@Test
public void separator() throws Exception {
File file = new File("src" + File.separator + "trials" + File.separator + "SlashTest.java");
assertThat(file.exists(), is(true));
}
}
Run Code Online (Sandbox Code Playgroud)
要重新解释这个问题,如果/适用于Unix和Windows,为什么要使用File.separator?
我想使用Java将文件从一个目录复制到另一个目录(子目录).我有一个目录,dir,带有文本文件.我在dir中遍历前20个文件,并希望将它们复制到dir目录中的另一个目录,这是我在迭代之前创建的.在代码中,我想复制review(代表第i个文本文件或审查)trainingDir.我怎样才能做到这一点?似乎没有这样的功能(或者我找不到).谢谢.
boolean success = false;
File[] reviews = dir.listFiles();
String trainingDir = dir.getAbsolutePath() + "/trainingData";
File trDir = new File(trainingDir);
success = trDir.mkdir();
for(int i = 1; i <= 20; i++) {
File review = reviews[i];
}
Run Code Online (Sandbox Code Playgroud) 我有一个阵列
File [] temp=null;
Run Code Online (Sandbox Code Playgroud)
我有一个File类型的arrayList
List <File> tempList = new ArrayList <File>();
Run Code Online (Sandbox Code Playgroud)
现在我想将内容从添加temp到tempList.所以任何人都可以请告诉我这是怎么回事?