Home >Java >javaTutorial >File operations in Java
Java is a programming language widely used in various fields such as web pages, mobile applications, and the Internet of Things. It has excellent cross-platform features and powerful file operation capabilities. This article will focus on file operations in Java.
File operations refer to reading, writing, creating, deleting and other related operations on files. File operations in Java are mainly implemented through the Java IO library. The Java IO library can be divided into two types: NIO and IO. The following will introduce the use of these two libraries in detail.
1. IO library
The IO library was introduced in Java 1.0. It is a set of class libraries used to implement input and output operations and provides various stream (Stream) operations. , we can read or write files through streams. The programming idea of IO library is oriented to byte stream (in byte), that is, for any type of data, it can only read and write byte data.
The File class in the Java IO library represents a file or directory in the file system. We can perform file-related operations through the File class, such as creating, deleting, renaming files, etc.
1.1 Create a file or directory
Corresponding to the new file or new directory operation in the file system, we can use the createNewFile() and mkdir() or mkdirs() methods in the File class to create file or directory.
• createNewFile() method: Creates a new file. If the file exists, it does not perform any operation and returns false.
The following code example creates a file named "test.txt":
File file = new File("test.txt"); boolean result = file.createNewFile(); System.out.println(result);
• mkdir() method: Creates a single-level directory. If the directory already exists, no operation is performed. .
The following code example creates a directory named "example":
File file = new File("example"); boolean result = file.mkdir(); System.out.println(result);
• mkdirs() method: Creates a multi-level directory, and does nothing if the directory already exists.
The following code example creates a directory named "example/child":
File file = new File("example/child"); boolean result = file.mkdirs(); System.out.println(result);
1.2 Deleting a file or directory
Corresponds to deleting a file or directory in the file system To delete a directory, we can use the delete() method in the File class to delete a file or directory.
The following code example deletes the file "test.txt":
File file = new File("test.txt"); boolean result = file.delete(); System.out.println(result);
1.3 Rename a file or directory
Corresponds to the rename file or directory operation in the file system , we can use the renameTo() method in the File class.
The following code example renames "test.txt" to "test1.txt":
File file = new File("test.txt"); File newFile = new File("test1.txt"); boolean result = file.renameTo(newFile); System.out.println(result);
Java IO library Provides a rich set of byte stream and character stream classes for reading and writing files.
2.1 Byte stream
Byte stream operates data in bytes. Common byte streams include FileInputStream, FileOutputStream, BufferedInputStream and BufferedOutputStream.
• FileInputStream
FileInputStream is a subclass of InputStream, which is used to convert input data into a byte stream and read file contents. We can create a file input stream object using the constructor of the FileInputStream class.
The following code example implements using FileInputStream to read the contents of a file:
FileInputStream fis = new FileInputStream("test.txt"); int data; while ((data = fis.read()) != -1) { System.out.print((char) data); } fis.close();
• FileOutputStream
FileOutputStream is a subclass of OutputStream, which is used to output data Convert to byte stream and write to file. We can create a file output stream object using the constructor of the FileOutputStream class.
The following code example implements using FileOutputStream to write strings to files:
String text = "Hello World!"; byte[] bytes = text.getBytes(); FileOutputStream fos = new FileOutputStream("test.txt"); fos.write(bytes); fos.close();
2.2 Character stream
Character stream operates data in character units, common character streams There are FileReader, FileWriter, BufferedReader and BufferedWriter.
• FileReader
FileReader is a subclass of Reader, which is used to read the character stream of a file. We can create a file input stream object using the constructor of the FileReader class.
The following code example implements using FileReader to read the contents of a file:
FileReader fr = new FileReader("test.txt"); int data; while ((data = fr.read()) != -1) { System.out.print((char) data); } fr.close();
• FileWriter
FileWriter is a subclass of Writer, which is used to write strings into the file. We can create a file output stream object using the constructor of the FileWriter class.
The following code example implements using FileWriter to write strings to files:
String text = "Hello World!"; FileWriter fw = new FileWriter("test.txt"); fw.write(text); fw.close();
2. NIO library
NIO library (New Input/Output) is in Java 1.4 Introduced in the version, it is a further encapsulation of the Java IO library, providing a more flexible and efficient operation mode, supporting non-blocking IO operations, and supporting simultaneous read and write operations. Compared with the IO library, the programming idea of the NIO library is oriented to the buffer area (ByteBuffer).
The file operation in the NIO library is similar to the IO library, and the File class is also used for file-related operations. The NIO library is more efficient than the IO library, so it is more suitable for processing large files.
1.1 Create a file or directory
Corresponding to the new file or new directory operation in the file system, we can use the createNewFile() and mkdir() or mkdirs() methods in the File class to create File or directory, the operation method is the same as the IO library.
1.2 Deleting files or directories
Corresponds to the deletion of files or deletion of directories in the file system. We can use the delete() method in the File class to delete files or directories. The operation method is the same as IO. library.
1.3 Rename a file or directory
Corresponding to the rename file or directory operation in the file system, we can use the renameTo() method in the File class, and the operation method is the same as the IO library.
同样的,NIO库也提供了丰富的字节流和字符流类,用于进行文件的读写操作。
2.1 字节流
NIO库中的字节流类主要是基于通道和缓冲区(Buffer)的操作方式,常见的字节流类有FileChannel和ByteBuffer。
• FileChannel
FileChannel用于读写文件数据,它通常与ByteBuffer配合使用。我们可以使用FileChannel的open()方法创建文件通道。
下面的代码示例实现了使用FileChannel读取文件中的内容:
File file = new File("test.txt"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel fc = raf.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int data; while ((data = fc.read(buffer)) != -1) { buffer.flip(); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } buffer.clear(); } fc.close(); raf.close();
• ByteBuffer
ByteBuffer提供了缓冲区,可用于读写文件数据。我们可以使用ByteBuffer的allocate()方法创建缓冲区。
下面的代码示例实现了使用ByteBuffer将字符串写入文件:
File file = new File("test.txt"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel fc = raf.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); String text = "Hello World!"; buffer.put(text.getBytes()); buffer.flip(); fc.write(buffer); fc.close(); raf.close();
2.2 字符流
NIO库中的字符流类主要是基于通道和缓冲区(Buffer)的操作方式,常见的字符流类有FileChannel、Charset和CharBuffer。
• FileChannel与ByteBuffer
它的操作方式同字节流,只是在使用ByteBuffer的时候需要设置编码方式,如下:
File file = new File("test.txt"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel fc = raf.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put("Hello World!".getBytes("UTF-8")); buffer.flip(); CharBuffer charBuffer = Charset.forName("UTF-8").decode(buffer); System.out.println(charBuffer.toString()); fc.close(); raf.close();
这段代码利用ByteBuffer将字符串写入文件,再将其通过Charset进行解码,创建Java字符串并输出。
• CharBuffer
CharBuffer同ByteBuffer类似,提供了缓冲区,可用于读写文件数据。其用法同ByteBuffer。
File file = new File("test.txt"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel fc = raf.getChannel(); CharBuffer buffer = CharBuffer.allocate(1024); String text = "Hello World!"; buffer.put(text); buffer.flip(); fc.write(Charset.forName("UTF-8").encode(buffer)); fc.close(); raf.close();
这段代码利用CharBuffer将字符串写入文件。
总结
Java IO库和NIO库各有优缺点,IO库操作简单而且容易理解,但是在处理大文件时效率较低;而NIO库操作稍微复杂,但是在处理大文件时更为高效。开发者可以根据自己实际需求选择合适的库进行文件操作。
The above is the detailed content of File operations in Java. For more information, please follow other related articles on the PHP Chinese website!