01: Use BufferedReader rather than FileReader
Example:
…
sourceBR =
new BufferedReader(
new FileReader(sourceFile));
while((data = sourceBR.readLine()) != null) {
System.out.println(data);
}
…
Rationale:
BufferedReader class is used to make low-level Reader classes like FileReader more efficient and easier to use. Compared to FileReaders, BufferedReaders read relatively chunks of data from a file at once, and keep this data in a buffer. When requested for next character or line of data, it is retrieved from the buffer, which minimizes the number of times that file-intensive, file read operations are performed. In addition, BufferedReader provides more convenient methods such as readLine(), that allow you to get next line of characters from a file.
02: Reading File with Multi-lingual Data should be done using InputStreamReader with a Character Set.
Example:
…
sourceBR =
new BufferedReader(
new InputStreamReader(
new FileInputStream(sourceFile), "ISO-8859-1"));
while((data = sourceBR.readLine()) != null) {
System.out.println(data);
}
…
Rationale:
InputStreamReader has various constructors where you can define the character set details along with the InputStream implementor. For File IO, we have used a FileInputStream with ISO-8859-1 as the character set. You can use any of the overloaded constructors with any flavored character set such as UTF8.
03: Use BufferedWriter or PrintWriter rather than FileWriter
Example:
…
sourcePW = new PrintWriter(sourceFile);
for(int i = 1; i <= 1000; i++) {
sourcePW.println("Wishing Hello World " + i + " times.");
}
sourcePW.flush();
…
Rationale:
BufferedWriter class is used to make lower-level classes like like FileWriters more efficient and easier to use. Compared to FileWriters, BufferedWriters write relatively large chunks of data to a file at once, minimizing the number of times that slow, file writing operations are performed. BufferedWriter classes also provides a newLine() method to create platform-specific line separators automatically.
This class has been enhanced significantly in Java 5. Because of newly created methods and constructors (like building a PrintWriter with a File or a String). New methods like format(), printf() and append() make PrintWriters very flexible and powerful.
For quick useful differences for both the wrapper writers please refer Reference Name ‘FILEIO_1’ for the link available in Appendix A under section File IO.
04: Always invoke flush() method after the business logic is completed and not in the finally.
Example:
…
1. try {
2. sourceFileReader = new FileReader(sourceFile);
3. sourceBR = new BufferedReader(sourceFileReader);
4. destinationPW = new PrintWriter(destinationFile);
5. while((data = sourceBR.readLine()) != null) {
6. destinationPW.println(data);
7. }
8. destinationPW.flush();
9. } catch(FileNotFoundException fnfException) {
10. …
11. } catch(IOException ioException) {
12. …
13. } finally {
14. try {
15. sourceFileReader.close();
16. sourceBR.close();
17. } catch(IOException ioException) {
18. …
19. }
20. destinationPW.close();
21. …
Rationale:
In the above sample program, we are committing the write operation by invoking the flush() method on the PrintWriter on line 8 and not in the finally block.
05: Never close the Reader or the Writer in the normal code block. Always close the resource in the finally bock to avoid open resources in memo.
Example:
1. File sourceDir = new File("C:\\FilePlay\\Source");
2. File sourceFile = new File(sourceDir, "Local_EN.txt");
3. File destinationDir = new File("C:\\FilePlay\\Destination");
4. destinationDir.mkdir();
5. File destinationFile = new File(destinationDir, "Local_EN.txt");
6. FileReader sourceFileReader = null;
7. BufferedReader sourceBR = null;
8. PrintWriter destinationPW = null;
9. String data = null;
10. try {
11. sourceFileReader = new FileReader(sourceFile);
12. sourceBR = new BufferedReader(sourceFileReader);
13. destinationPW = new PrintWriter(destinationFile);
14. while((data = sourceBR.readLine()) != null) {
15. destinationPW.println(data);
16. }
17. destinationPW.flush();
18. } catch(FileNotFoundException fnfException) {
19. fnfException.printStackTrace();
20. } catch(IOException ioException) {
21. ioException.printStackTrace();
22. } finally {
23. try {
24. sourceFileReader.close();
25. sourceBR.close();
26. } catch(IOException ioException) {
27. ioException.printStackTrace();
28. }
29. destinationPW.close();
30. }
Rationale:
In the above sample program, we are committing the write operation by invoking the flush() method on the PrintWriter on line 17 but the FileReader & BufferedReader along with the PrintWriter resources’ closure is done in the finally block at lines 24, 25 & 29.
In case of course grained methods the resources can be closed after performing reading/writing operations but still close it in the finally block.
Garbage Collector will sweep these method local resources any-ways but it is considered as good coding standard to close the opened resources.
06: Use native OS Merging files commands rather than writing separate Java program to perform the merging operation.
Examples
…
cat file1 >> file2 && cat file2 >> file3
…
Rationale
File merging operation is specific to the Operating System and the same is much faster than writing a separate Java program. Above is an example of UNIX OS where multiple files that were written by individual threads participating in a single File creation process are merged for FTP. Please note to do the necessary POC in the respective deployment environment prior to production.
Please note, considering that each 0f the 3 files hold 10 records, that in the above command, file1 data will be first copied to file2 and not moved and then file2 data will be copied to file3 and not moved. At the end, now file 1 will still have 10 records, file2 will have 20 and file3 will have 30 records. Therefore, file1 and file2 has to be deleted post this operation.
07: Always check the file status prior to reading the file incase it is being downloaded via any channel say FTP or HTTP.
Examples
Put a finisher identifier so that the client program(s) can lookup for the character/string and conclude that the download is done. Example: ‘0’, ‘#’, Trailer/Summary text
Implement the client program that looks at the file size with an interval of say 10 seconds and if the size is same for 3 consecutive times then conclude that the download or file operation is over.
Rationale
Rationale behind checking the file is to ensure that the client is always working on the full data and not the partial data.
08: Never read a huge file completely in memory
Rationale:
Reading a huge file completely in memory should be avoided as an OutOfMemoryError could be thrown and that could crash the JVM. Rather, a multi-threaded file processing approach should be adopted as displayed in the figure above.
Here, the File Reader reads the data and puts it in a Data Cache where it will be held in a synchronized collection. Multiple processing threads will pop (read and remove) the data from this synchronized collection for processing.
相关推荐
java file,java读取txt文档,java操作txt文档,读取文档的内容
对java.io.File类的操作
java io file 文件复制,可直接运行。java io file 文件复制,可直接运行。
Java实验指导(4)-io流.pdf
java.io clojure.java.io 的 JK7 java.nio.file.Path 兼容性依赖信息该库托管在 Releases 上。 依赖: [me.moocar/java.io " 0.1.0 " ]用法是 JDK7 中引入的文件路径的抽象。 这个库提供了和 Paths 之间的兼容性。 ...
尽管java.io定义的大多数类是实行流式操作的,File类不是。它直接处理文件和文件系统。也就是说,File类没有指定信息怎样从文件读取或向文件存储;它描述了文件本身的属性。File对象用来获取或处理与磁盘文件相关的...
Java文件io-stream-file教程
java file类java file类java file类操作实例
Java基础IO流之File类的使用
文件输入输出,写的一个例子,关于streamread,streamwrite的使用。
Java实现文件复制,File文件读取,写入,IO流的读取写入
fileio is the verilog file
java.io包中的File类.doc
了解java.io包 运用File类对文件或目录的属性进行操作 理解流,理解输入/输出流的概念 运用FileInputStream类和FileOutputStream类读/写字节文件 运用FileReader类和FileWriter类配合BufferedReader类和...
java做的简单文件IO操作,实现文件的读写追加功能。 压缩包里面有程序运行时的截图。
File关于IO流的源码,详细的讲解也有,很多的注释,适合初学者,本人也是初学者,慢慢学
C# File 类 (System_IO)
51 import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; @SuppressWarnings("serial") //一个类要想实现序列...
Java 中的一些基本文件操作,包括:文件操作(移动、读写)和文本文件读写
对Java IO流操作感兴趣的开发人员 需要进行文件读写、网络传输等IO操作的程序员 使用场景 该代码资源可以用于教学、自学以及实际项目开发中的参考。 教学:作为教学示例演示给学生 自学:通过查看示例代码来学习和...