Java函数库中如何进行文件读写操作?
在Java中进行文件读写操作主要有以下两种方式:
1. 使用 Java I/O Streams
Java I/O Streams是一组类库,用于读取和写入数据流(如FileInputStream和FileOutputStream)。这种方法可以读取和写入单个字节或字节数组。我们可以使用以下方式读取文件:
FileInputStream fis = null;
try {
fis = new FileInputStream("file.txt");
int data = fis.read();
while(data != -1) {
System.out.print((char) data);
data = fis.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if(fis!=null)
fis.close();
}
在上述代码中,我们使用FileInputStream来打开文件并进行读取。在读取时,每次读取一个字节,并将其转换为字符,直到文件读取完毕。
写入文件的方式与读取数据的方式类似:
FileOutputStream fos = null;
try {
String str = "Hello world!";
byte[] byteArray = str.getBytes();
fos = new FileOutputStream("file.txt");
fos.write(byteArray);
System.out.println("File Written Successfully");
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(fos != null) {
fos.close();
}
} catch(IOException ioe) {
System.out.println("Error in closing the Stream");
}
}
在上述代码中,我们将字符串转换为字节数组,然后使用FileOutputStream将数据写入到指定的文件中。
2. 使用 Java NIO
Java NIO是Java 1.4以上版本中提供的一组新的I/O API。它提供了更高效、更灵活的I/O操作方式。Java NIO提供了两种方式进行文件读写操作:通道(Channel)和缓冲区(Buffer)。
我们可以使用以下方式读取文件:
RandomAccessFile aFile = null;
try {
aFile = new RandomAccessFile("file.txt", "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(inChannel.read(buffer) > 0) {
buffer.flip();
while(buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear();
}
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(aFile!=null)
aFile.close();
} catch(IOException e) {
e.printStackTrace();
}
}
在上述代码中,我们首先通过RandomAccessFile读取文件。然后通过FileChannel来实例化缓冲区ByteBuffer,设置缓冲区大小为1024字节。接下来,我们通过循环方式读取文件中的数据,并将数据存储在缓冲区中。最后,我们使用flip()方法将指针回退至缓冲区的初始位置,并使用hasRemaining()和get()方法读取缓冲区中的数据。
写入文件的方式与读取数据的方式类似:
RandomAccessFile aFile = null;
try {
String str = "Hello World!";
aFile = new RandomAccessFile("file.txt", "rw");
FileChannel outChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put(str.getBytes());
buffer.flip();
outChannel.write(buffer);
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(aFile != null) {
aFile.close();
}
} catch(IOException e) {
e.printStackTrace();
}
}
在上述代码中,我们首先将字符串转换为字节数组,并创建ByteBuffer对象。然后,我们通过读写通道将数据写入指定的文件。最后,我们使用flip()方法将指针回退至缓冲区的初始位置,并使用write()方法将数据写入文件中。
总结:
Java的I/O类库提供了多种方式进行文件读写操作。其中Java I/O Streams和Java NIO提供了不同的特点和优势。选择哪一种方法应根据需要进行权衡。
