Java读写3行文件

it2022-05-05  169

假设我们现在想从文件1读取3行内容,然后写入文件2。我们应该怎么做?

代码如下:

import java.io.*; public class ReadAndWriteFile { /** * 从源文件读写三行内容,复制到目标文件。 * 执行成功返回true,执行失败返回false * * @param sourceFilePath 源文件路径 * @param destinationFilePath 目标文件路径 * @return * @throws IOException */ public static boolean ReadAndWriteFile(String sourceFilePath, String destinationFilePath) throws IOException { /* 输入校验 */ if (sourceFilePath == null || sourceFilePath == "" || destinationFilePath == null || destinationFilePath == "") { return false; } /* 初始化 */ File sourceFile = new File(sourceFilePath); File destinationFile = new File(destinationFilePath); FileInputStream fileInputStream = null; //FileInputStream负责 从文件系统中的文件,获取输入字节。将文件转换为字节流 InputStreamReader inputStreamReader = null;//InputStreamReader负责 将字节流转换成字符流。读取字节,并且按指定的字符集来将字节解码成字符 BufferedReader bufferedReader = null; //BufferedReader负责 从字符输入流中读取文本,缓冲字符,以便有效地读取字符、数组和行。 FileOutputStream fileOutputStream = null; //文件输出流是用于将数据写入文件或 FileDescriptor的输出流 OutputStreamWriter outputStreamWriter = null; //将字符流 转换成 字节流。并按照指定的字符集 将字符编码成字节。 BufferedWriter bufferedWriter = null; //将文本写入字符输出流,缓冲字符,以便有效地写入单个字符、数组和字符串。 try { /* 文件合法性判断 */ if (sourceFile.isFile() && sourceFile.exists()) { /* 如果目标文件不存在,那就创建一个目标文件 */ if (!destinationFile.exists()) { destinationFile.createNewFile(); }else if (!destinationFile.isFile()){ /* 如果目标文件存在,但不是一个文件。(可能是一个目录,但我们不能直接往目录里面写文件)*/ return false; } /*将文件中的数据缓存到bufferedReader中,然后从bufferedReader中读数据*/ fileInputStream = new FileInputStream(sourceFile); /* 获取文件输入流 */ inputStreamReader = new InputStreamReader(fileInputStream, "gb2312"); //避免中文乱码。 bufferedReader = new BufferedReader(inputStreamReader); /* 将通过bufferedWriter,向文件中写入数据 */ fileOutputStream = new FileOutputStream(destinationFile); outputStreamWriter = new OutputStreamWriter(fileOutputStream, "gb2312"); bufferedWriter = new BufferedWriter(outputStreamWriter); /* 从源文件中读3行内容,然后写入到目标文件中 */ int count = 0; String line = null; while (count < 3 && ((line = bufferedReader.readLine()) != null)) { //从缓存字符流中,读一行字符 System.out.println(line); bufferedWriter.write(line + System.getProperty("line.separator"));//在读出来的一行的 末尾,加入换行符。不然文件是不换行地连成一句话 count++; } return true; //读写成功,返回true } else { System.out.println("文件不合法"); return false; } } catch (IOException e) { e.printStackTrace(); return false; } finally { /** * 注意关闭顺序。最先打开的资源最后关闭,最后打开的资源最先关闭。 * 否则会报 java.io.IOException: Stream closed 异常 */ try { if (bufferedWriter != null) { //先要进行非空判断,不然会报空指针异常 bufferedWriter.close(); } if (outputStreamWriter != null) { outputStreamWriter.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } if (bufferedReader != null) { bufferedReader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } if (fileInputStream != null) { fileInputStream.close(); } } catch (IOException e1) { e1.printStackTrace(); } } } public static void main(String[] args) throws IOException { //测试 //System.out.println(ReadAndWriteFile("D:\\Program Files (x86)\\JetBrains\\IOTest\\file1.txt", "D:\\Program Files (x86)\\JetBrains\\IOTest\\file2.txt")); //System.out.println(ReadAndWriteFile("D:\\Program Files (x86)\\JetBrains\\IOTest\\file1.txt", "")); System.out.println(ReadAndWriteFile("D:\\Program Files (x86)\\JetBrains\\IOTest\\file1.txt", "D:\\Program Files (x86)\\JetBrains\\IOTest\\file3.txt")); } }

首先执行下面的测试: 

System.out.println(ReadAndWriteFile("D:\\Program Files (x86)\\JetBrains\\IOTest\\file1.txt", "D:\\Program Files (x86)\\JetBrains\\IOTest\\file2.txt"));

测试结果如下: 

文件目录如下: 

文件1里面的内容如下:

文件2里面的内容如下: 

我们可以看到:我们成功的复制了file1.txt的前3行文件到file2.txt

 

接下来我们执行另一个测试:

System.out.println(ReadAndWriteFile("D:\\Program Files (x86)\\JetBrains\\IOTest\\file1.txt", "D:\\Program Files (x86)\\JetBrains\\IOTest\\file3.txt"));

 文件目录如下:

文件3的内容如下:

可见我们成功将文件写入了原来并不存在的 file3.txt 

 

接下来看一下原码中是怎么介绍,Java读写文件时 我们会用到的类和方法的:

File类

An abstract representation of file and directory pathnames.

文件和目录路径名的抽象表示。

 

FileInputStream类

A FileInputStream obtains input bytes from a file in a file system. What files are  available depends on the host environment.fileinputstream从文件系统中的文件中,获取 输入字节。哪些文件可用取决于主机环境。 FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader

FileInputStream用于读取原始字节流,如图像数据。对于读取字符流,请考虑使用FileReader

 

InputStreamReader

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

InputStreamReader是从字节流到字符流的桥梁:它读取字节并使用指定的字符集将其解码为字符。它使用的字符集可以通过名称指定,也可以显式给定,或者可以接受平台的默认字符集。

 

BufferedReader 类

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

从字符输入流中 读取文本,缓冲字符,以便有效地读取字符、数组和行。

The buffer size may be specified, or the default size may be used.  The default is large enough for most purposes.

可以指定缓冲区大小,也可以使用默认大小。默认值对于大多数用途来说都足够大。

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.  It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. 

通常,每个读卡器发出的读请求都会导致相应的读请求由底层字符或字节流发出。因此,建议将BufferedReader包装在任何read()操作可能代价高昂的Reader上,例如FileReaders和InputStreamReaders。

private static int defaultCharBufferSize = 8192;  //8*1024=8192

 

FileOutputStream 类

A file output stream is an output stream for writing data to a File or to a FileDescriptor.文件输出流是用于将数据写入 文件 或 文件描述符 的输出流 Whether or not a file is available or may be created depends upon the underlying platform.  Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time.  In such situations the constructors in this class will fail if the file involved is already open.

文件是否可用 或 是否可以创建取决于基础平台。某些平台尤其允许一次只打开一个文件进行写入(或其他文件写入对象)。在这种情况下,如果所涉及的文件已经被打开,则此类中的构造函数将失败。

 

OutputStreamWriter 类

An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.  The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

OutputStreamWriter是从字符流到字节流的桥梁:写入它的字符使用指定的字符集编码为字节。它使用的字符集可以通过名称指定,也可以显式给定,或者可以接受平台的默认字符集。

 

BufferedWriter 类

Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.将文本写入字符输出流,缓冲字符,以便有效地写入单个字符、数组和字符串。

The buffer size may be specified, or the default size may be accepted.The default is large enough for most purposes.可以指定缓冲区大小,也可以接受默认大小。默认大小足以满足大多数目的。

A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property <tt>line.separator</tt>. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.提供了newLine()方法,该方法使用平台自己的行分隔符概念,如系统属性 line.separator 所定义。并非所有平台都使用换行符(“\n”)终止行。因此,调用此方法以终止每个输出行,而不是直接编写换行符。

In general, a Writer sends its output immediately to the underlying character or byte stream.  Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. 

通常,Writer会立即将其输出发送到底层字符或字节流。除非需要提示输出,否则建议将BufferedWriter包装在writer()操作可能代价高昂的任何Writer上,如FileWriters和OutputStreamWriters。

 

File.isFile()

Tests whether the file denoted by this abstract pathname is a normal file.  A file is <em>normal</em> if it is not a directory and, in addition, satisfies other system-dependent criteria.  Any non-directory file created by a Java application is guaranteed to be a normal file.

测试此抽象路径名表示的文件是否为 normal file。如果文件不是一个目录,并且满足其他与系统相关的标准,则该文件是normal file 。Java应用程序创建的任何非目录文件都保证是一个普通文件。

 

File.exists()

Tests whether the file or directory denoted by this abstract pathname exists.

测试此抽象路径名指示的文件或目录是否存在。

 

bufferedReader.readLine()

Reads a line of text.  A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

读取一行文本。行被认为是由换行符(“\n”)、回车符(“\r”)或紧跟换行符的回车符中的任何一个终止的。

 

bufferedWriter.write(String str)

Writes a string.

往输出流写入字符串。

 

System.getProperty("line.separator")

Gets the system property indicated by the specified key.

获取由指定键指示的系统属性。

最后我想提醒一下:释放资源要在finall块中进行,而且资源要按照最后开的最先关闭的顺序来关闭。不然程序会报错。


 

觉得对你有帮助的话,请给我点个关注吧~

 


最新回复(0)