如何在Java中读取一个文件的数据并打印到另一个文件中?
Java提供I/O流来读取和写入数据,其中流代表输入源或输出目标,可以是文件、I/O设备、其他程序等。
一般来说,流可以是输入流或输出流。
InputStream − 用于从源读取数据。
OutputStream − 用于将数据写入目标。
根据它们处理的数据,流有两种类型:
字节流 − 这些流以字节(8位)处理数据,即字节流类读取/写入8位数据。使用这些流,您可以存储字符、视频、音频、图像等。
字符流 − 这些流以16位Unicode处理数据。使用这些流,您只能读取和写入文本数据。
下图说明了Java中所有输入和输出流(类)。
其中,您可以使用Scanner、BufferedReader和FileReader类读取文件内容。
同样,您可以使用BufferedWriter、FileOutputStream、FileWriter将数据写入文件。
将一个文件的内容写入另一个文件
以下是一个Java程序,它使用Scanner类将文件数据读取到字符串中,并使用FileWriter类将其写入另一个文件中。
示例
import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class CopyContent { public static void main(String[] args) throws IOException { //Instantiating a file class File file = new File("D:\sampleData.txt"); //Instantiate an FileInputStream class FileInputStream inputStream = new FileInputStream(file); //Instantiating the Scanner class Scanner sc = new Scanner(inputStream); //StringBuffer to store the contents StringBuffer buffer = new StringBuffer(); //Appending each line to the buffer while(sc.hasNext()) { buffer.append(" "+sc.nextLine()); } System.out.println("Contents of the file: "+buffer); //Creating a File object to hold the destination file File dest = new File("D:\outputFile.txt"); //Instantiating an FileWriter object FileWriter writer = new FileWriter(dest); //Writing content to the destination writer.write(buffer.toString()); writer.flush(); System.out.println("File copied successfully......."); } }
输出
Contents of the file: Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more. 40 million readers read 100 million pages every month. Our content and resources are freely available and we prefer to keep it that way to encourage our readers acquire as many skills as they would like to. We don’t force our readers to sign up with us or submit their details either. No preconditions and no impediments. Simply Easy Learning! File copied successfully.......
广告