在Java中将内容从一个文件复制到另一个文件的不同方法
在Java中,我们可以将一个文件的内容复制到另一个文件中。这可以通过 FileInputStream 来完成 和FileOutputStream类。
FileInputStream 类
它是一个字节输入流类,有助于从文件中读取字节。它提供了从文件中读取数据的不同方法。
FileInputStream fin = new FileInputStream(filename);
这将创建一个 FileInputStream 对象fin给它一个文件名,它将从中复制内容或执行读取操作。
使用的方法:
1. read():该方法用于读取一个字节的数据。它将该字节作为整数值返回,如果到达文件末尾,则返回-1 。
2.close():该方法用于关闭FileInputStream。
FileOutputStream 类
它是一个字节输出流类,有助于将字节写入文件。它提供了将数据写入文件的不同功能。
FileOutputStream fout = new FileOutputStream(filename);
这将创建一个 FileOutputStream 对象fout给定一个文件名,它将写入读取的内容。
使用的方法:
1. write():该方法用于向FileOutputStream写入一个字节的数据。
2.close():该方法用于关闭FileInputStream。
文件类
File f = new File(filename);
这将创建一个名为f 的 File 对象,给定一个字符串对象,该对象是要访问的该文件的文件名或位置路径。
注意:如果此处给出的文件名不存在,则File类将创建一个具有该名称的新文件。
例子:
Java
// Java program to copy content from
// one file to another
import java.io.*;
import java.util.*;
public class CopyFromFileaToFileb {
public static void copyContent(File a, File b)
throws Exception
{
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);
try {
int n;
// read() function to read the
// byte of data
while ((n = in.read()) != -1) {
// write() function to write
// the byte of data
out.write(n);
}
}
finally {
if (in != null) {
// close() function to close the
// stream
in.close();
}
// close() function to close
// the stream
if (out != null) {
out.close();
}
}
System.out.println("File Copied");
}
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
// get the source file name
System.out.println(
"Enter the source filename from where you have to read/copy :");
String a = sc.nextLine();
// source file
File x = new File(a);
// get the destination file name
System.out.println(
"Enter the destination filename where you have to write/paste :");
String b = sc.nextLine();
// destination file
File y = new File(b);
// method called to copy the
// contents from x to y
copyContent(x, y);
}
}
输出
Enter the source filename from where you have to read/copy :
sourcefile.txt
Enter the destination filename where you have to write/paste :
destinationfile.txt
File Copied
源文件
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/Different_Ways_to_Copy_Content_From_One_File_to_Another_File_in_Java_0.jpg)
源文件
目标文件
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/Different_Ways_to_Copy_Content_From_One_File_to_Another_File_in_Java_1.jpg)
目标文件