java实现 读取一个文件,copy到一个新目录下,如果新目录下文件存在则追加内容,不存在则copy
时间: 2023-07-18 13:07:07 浏览: 123
可以使用Java的File类和IO流来实现这个功能。具体实现步骤如下:
1. 创建一个File对象,表示要读取的文件。
2. 创建一个FileInputStream对象,用于读取文件内容。
3. 创建一个File对象,表示要写入的文件。
4. 判断要写入的文件是否存在。
5. 如果文件不存在,则创建一个新文件;如果文件存在,则创建一个FileOutputStream对象,并设置为追加模式。
6. 创建一个byte数组,用于存储读取的文件内容。
7. 循环读取文件内容,直到读取完毕。
8. 将读取到的内容写入到目标文件中。
9. 关闭输入流和输出流。
代码如下:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String srcFilePath = "/path/to/source/file";
String destDirPath = "/path/to/destination/directory";
String destFileName = "newfile.txt";
File srcFile = new File(srcFilePath);
File destDir = new File(destDirPath);
File destFile = new File(destDir, destFileName);
try {
FileInputStream fis = new FileInputStream(srcFile);
if (!destFile.exists()) {
destFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(destFile, true);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
需要注意的是,在创建FileOutputStream对象时,如果第二个参数为true,则表示以追加模式打开文件。这样就可以将读取到的内容追加到目标文件中。如果第二个参数为false,则表示以覆盖模式打开文件,读取到的内容会覆盖原有内容。
阅读全文
相关推荐


















