`
maosheng
  • 浏览: 565431 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java File IO开发指导

    博客分类:
  • Java
 
阅读更多

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实验指导(4)-io流.pdf

    虽然在给定的实验内容中没有直接使用它们,但在实际开发中,通常会使用这些类来批量读取或写入数据,以减少磁盘访问次数。 4. **RandomAccessFile**:这个类允许随机访问文件中的任何位置,不仅支持读取,也支持...

    Java实验指导(4)-io流.doc

    ### Java 实验指导 (4) - IO 流 #### 实验背景与目标 在 Java 编程中,I/O(Input/Output)流是处理数据输入输出的核心技术之一。掌握 I/O 流对于进行文件操作、网络通信等非常重要。本实验旨在通过一系列实践练习...

    Scalable IO in Java doug lea.zip

    通过学习《Scalable IO in Java》,开发者能够掌握如何在Java应用程序中有效地利用NIO进行高性能的I/O操作,这对于构建大型、高并发的网络服务,如Web服务器、数据库服务器等,具有重要的指导意义。不过,由于书籍为...

    Java案例开发_项目开发风暴(PDF).

    《Java案例开发_项目开发风暴》是一份深入探讨Java编程技术及实际项目开发经验的PDF文档,旨在帮助读者提升在Java领域的实践技能。本资料详细介绍了多种Java编程技术和实际应用场景,通过实例分析和项目实战,让学习...

    java上机实践指导图文教程

    此外,Java还包含丰富的标准库,如IO、NIO、网络编程、XML处理、数据库连接(JDBC)等,这些都是Java开发者必须掌握的知识。 最后,NIIT的学习者还需要了解如何进行单元测试,使用JUnit框架来验证代码的正确性,...

    JAVA程序设计实验指导书

    Java是一种广泛应用于各种领域的面向对象编程语言,它的跨平台特性使得它在软件开发中具有极高的灵活性和实用性。以下我们将探讨该指导书中可能涉及的主要知识点: 1. **基础语法**:Java的基础语法是学习的起点,...

    Java经典开发全集.7z

    5. **IO与NIO**:Java的输入输出系统是处理文件和网络通信的基础,包括File类、InputStream/OutputStream、Reader/Writer,以及后来的非阻塞IO(NIO)API,如Channels、Buffers等。 6. **多线程编程**:Java提供了...

    java文档 html格式

    当需要读写文件时,`java.io`包的文档会指导你如何使用流来完成任务。此外,文档还包含了异常处理的部分,帮助开发者理解何时及如何抛出和捕获异常,以及如何正确使用`try-catch-finally`语句。 Java API文档的另一...

    java开发实战经典笔记整理

    这些知识点涵盖了Java开发的多个层面,从基础语法到高级特性的应用,对于深入学习Java编程和进行实际项目开发具有重要指导价值。通过阅读并实践这些笔记,你将能够提升自己的Java开发能力,更好地应对各种编程挑战。

    Java编程必备之帮助文档

    "Java编程必备之帮助文档"正是这样的资源,它提供了关于Java语言的全面信息,包括语法、类库、接口和方法等,对于日常开发工作具有极大的指导价值。 "Java编程必备之帮助文档"主要包含了Java API(Application ...

    2009年java认证考试重点指导

    Java认证考试,全称为Oracle Certified Professional, Java SE 8 Programmer,是Java开发人员为了证明其在Java编程领域的专业技能和知识而参加的一项考试。2009年的Java认证考试主要针对的是Java SE 6,虽然现在已经...

    javaAPI大全,从基础到开发

    总的来说,Java API大全是Java开发者的重要参考资源,无论是在学习过程中还是在项目开发中,它都能提供详尽的指导和帮助。通过对这些API的理解和实践,开发者能够构建出稳定、高效且易于维护的Java应用程序。

    Java实现字节流与图片的转化Java实用源码整理learns.

    总的来说,通过学习这个资料包,你将能够掌握Java中字节流与图片转化的关键技术,这对于开发涉及文件操作或网络传输的Java应用程序是非常重要的。记得实践是检验真理的唯一标准,动手尝试并理解这些代码,将对你的...

    基于Java的FTP客户端源代码

    Java提供了一系列的API,如`java.net.Socket`和`java.io`包中的类,使得开发FTP客户端成为可能。在本文中,我们将深入探讨如何使用Java实现FTP客户端,并通过实际的代码示例来解释关键概念。 首先,理解FTP的工作...

    用java写的进行文件处理的代码

    import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; ``` 这里导入了所有用于文件读写的必要类,包括`BufferedReader`、`...

    Java 远程文件对接

    - 使用`java.io.File`类创建文件对象。 - 利用`java.io.FileInputStream`或`java.io.FileOutputStream`进行文件的读写操作。 2. **异常处理**: - 处理文件操作时可能会遇到的异常,如`FileNotFoundException`...

    java语言程序设计 郭克华版 入门及实践指导1

    Java语言程序设计,郭克华版的入门及实践指导,是初学者掌握Java编程的宝贵资源。这本书籍结合了理论与实践,旨在帮助读者...通过逐步学习和实践这些知识点,将能够逐步掌握Java编程,并为更高级的开发打下坚实的基础。

    Java(jdk)多页面记事本以及项目文档

    2. 文件操作:Java的java.io包提供了File、BufferedReader和 BufferedWriter等类,用于实现文件的读写操作。在多页面记事本中,每个页面的数据会保存到单独的文件中,读取文件时,数据加载到对应的文本区域,保存...

    JAVA程序设计(慕课版)课后习题答案

    总的来说,这个“JAVA程序设计(慕课版)课后习题答案”集合将涵盖以上所有这些Java编程的核心概念和实践技能,对于提高编程能力、解决实际问题以及为后续的Java项目开发打下坚实基础大有裨益。通过解答这些习题,...

Global site tag (gtag.js) - Google Analytics