欢迎访问宙启技术站
智能推送

使用Java函数操作文件输入输出流

发布时间:2023-08-12 17:37:09

在Java中,可以使用FileInputStream和FileOutputStream类来进行文件的输入输出操作。

FileInputStream类用于从文件中读取数据,它继承自InputStream类。可以使用以下代码创建一个FileInputStream对象并读取文件中的内容:

try {
    FileInputStream fis = new FileInputStream("file.txt");
    int data;
    while ((data = fis.read()) != -1) {
        System.out.print((char) data);
    }
    fis.close();
} catch (IOException e) {
    e.printStackTrace();
}

在以上代码中,我们首先创建了一个FileInputStream对象,并将要读取的文件名传递给它的构造函数。然后使用read()方法读取文件中的数据,每次读取一个字节,直到读取到文件的末尾(read()方法返回-1)。最后,使用close()方法关闭输入流。

FileOutputStream类用于向文件中写入数据,它继承自OutputStream类。可以使用以下代码创建一个FileOutputStream对象并写入数据到文件中:

try {
    FileOutputStream fos = new FileOutputStream("file.txt");
    String data = "Hello, World!";
    fos.write(data.getBytes());
    fos.close();
} catch (IOException e) {
    e.printStackTrace();
}

在以上代码中,我们首先创建了一个FileOutputStream对象,并将要写入的文件名传递给它的构造函数。然后,使用write()方法将数据写入到文件中。在这个例子中,我们将一个字符串转换为字节数组,并将字节数组写入到文件中。最后,使用close()方法关闭输出流。

除了基本的读写操作外,还可以使用BufferedInputStream和BufferedOutputStream类来提高读写的效率。例如,可以使用BufferedInputStream类读取数据,可以使用BufferedOutputStream类写入数据。

try {
    FileInputStream fis = new FileInputStream("file.txt");
    BufferedInputStream bis = new BufferedInputStream(fis);
    int data;
    while ((data = bis.read()) != -1) {
        System.out.print((char) data);
    }
    bis.close();
    fis.close();
} catch (IOException e) {
    e.printStackTrace();
}

try {
    FileOutputStream fos = new FileOutputStream("file.txt");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    String data = "Hello, World!";
    bos.write(data.getBytes());
    bos.close();
    fos.close();
} catch (IOException e) {
    e.printStackTrace();
}

以上代码中,我们首先创建了一个BufferedInputStream对象或BufferedOutputStream对象,并将FileInputStream对象或FileOutputStream对象作为参数传递给它的构造函数。然后,可以像之前的例子一样使用read()或write()方法来读写数据。

除了使用以上的同步输入输出流外,还可以使用Java的NIO(New IO)类来进行文件的异步输入输出操作。使用FileChannel类可以读写文件中的数据,并且可以使用ByteBuffer类来处理数据的缓冲区。

try {
    RandomAccessFile file = new RandomAccessFile("file.txt", "rw");
    FileChannel channel = file.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    while (channel.read(buffer) != -1) {
        buffer.flip(); // 切换到读模式
        while (buffer.hasRemaining()) {
            System.out.print((char) buffer.get());
        }
        buffer.clear(); // 清空缓冲区,并切换到写模式
    }
    channel.close();
    file.close();
} catch (IOException e) {
    e.printStackTrace();
}

try {
    RandomAccessFile file = new RandomAccessFile("file.txt", "rw");
    FileChannel channel = file.getChannel();
    String data = "Hello, World!";
    ByteBuffer buffer = ByteBuffer.wrap(data.getBytes());
    channel.write(buffer);
    channel.close();
    file.close();
} catch (IOException e) {
    e.printStackTrace();
}

以上代码中,我们首先创建了一个RandomAccessFile对象,并将要读取或写入的文件名和模式("rw"表示可读写)传递给它的构造函数。然后,使用getChannel()方法获取文件的通道(FileChannel对象)。接下来,可以使用read()或write()方法来读写文件的通道。

这是关于使用Java函数操作文件输入输出流的一些基本介绍。