输出流复制文件

11.16

输出流复制文件

今天练习的是使用输出流复制文件:

代码部分:

package lianxi;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class bo
{
public void copyFiles(Path originPath, Path destinationPath)
throws IOException {
if (Files.notExists(originPath)
|| Files.exists(destinationPath)) {
throw new IOException(
"Origin file must exist and " +
"Destination file must not exist");
}
byte[] readData = new byte[1024];
try (InputStream inputStream = Files.newInputStream(originPath,
StandardOpenOption.READ);
OutputStream outputStream = Files.newOutputStream(destinationPath,
StandardOpenOption.CREATE)) {
int i = inputStream.read(readData);
while (i != -1) {
outputStream.write(readData, 0, i);
i = inputStream.read(readData);
}
} catch (IOException e) {
throw e;
}
}

public static void main(String[] args) {
bo test = new bo();
Path origin = Paths.get("D:/c.txt");
Path destination = Paths.get("D:/d.txt");
try {
test.copyFiles(origin, destination);
System.out.println("Copied Successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}

 运行结果:

 

 

 

 

 

 运行结果分析:

最后也是成功的吧C文件里的内荣复制到D文件里面了。

posted @ 2020-11-16 10:44  潘福龙  阅读(78)  评论(0编辑  收藏  举报