Java文件复制是Java中常用的操作之一,我们通常利用类库中的FileInputStream 和 FileOutputStream来实现文件拷贝。下面是Java文件复制代码片段的完整攻略:
步骤一:创建输入输出流对象
首先要创建输入输出流对象,读取原文件并将文件写入指定文件。这里我们使用Java中的FileInputStream和FileOutputStream。
FileInputStream inStream = new FileInputStream("sourceFile.txt");
FileOutputStream outStream = new FileOutputStream("targetFile.txt");
步骤二:读取输入流
读取源文件中的数据并将其保存在字节数组中。以下是将源文件中的数据读入字节数组的示例:
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
这段代码将原文件中的数据读入buffer中,直到数据读取到末尾。然后通过write方法将数据写入到targetFile.txt中。
步骤三:关闭输入输出流
复制完文件之后,可以将流关闭以释放其资源。以下是关闭流的示例:
inStream.close();
outStream.close();
完整的Java代码如下:
import java.io.*;
public class FileCopyDemo {
public static void main(String[] args) throws IOException {
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
File inputFile = new File("sourceFile.txt");
File outputFile = new File("targetFile.txt");
inStream = new FileInputStream(inputFile);
outStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
} finally {
if (inStream != null) inStream.close();
if (outStream != null) outStream.close();
}
}
}
示例1:将当前文件夹下名为source.png的图片文件复制到当前文件夹下的target.png文件中。
import java.io.*;
public class FileCopyDemo {
public static void main(String[] args) throws IOException {
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
File inputFile = new File("source.png");
File outputFile = new File("target.png");
inStream = new FileInputStream(inputFile);
outStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
} finally {
if (inStream != null) inStream.close();
if (outStream != null) outStream.close();
}
}
}
示例2:将当前文件夹下的名为source.txt的文件复制到当前文件夹下的target.txt文件中。
import java.io.*;
public class FileCopyDemo {
public static void main(String[] args) throws IOException {
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
File inputFile = new File("source.txt");
File outputFile = new File("target.txt");
inStream = new FileInputStream(inputFile);
outStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
} finally {
if (inStream != null) inStream.close();
if (outStream != null) outStream.close();
}
}
}
以上两个示例都遵循了Java文件复制的完整流程,可以更改文件名和路径实现更多的文件复制操作。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java文件复制代码片断(java实现文件拷贝) - Python技术站