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

Java中IO流函数的使用及其作用

发布时间:2023-06-25 15:15:49

Java的IO(Input/Output)流是Java语言中非常重要的部分,它允许Java程序与文件、网络、键盘、鼠标等外设进行输入输出操作。Java中的IO流是基于InputStream和OutputStream类的,其提供了InputStream和OutputStream的子类来实现文件操作、网络操作、内存操作等。

在Java中,IO流函数的使用非常丰富,以下是一些常用的IO流函数及其作用:

1. FileInputStream/FileOutputStream:用于读写文件,以字节为单位读写文件。如下面的代码实例:

import java.io.*;

public class FileInputOutputStreamTest {
    public static void main(String args[])throws IOException {
        FileInputStream in = null;
        FileOutputStream out = null;

        try {
            in = new FileInputStream("input.txt");
            out = new FileOutputStream("output.txt");

            int c;
            while ((c = in.read()) != -1) {
                out.write(c);
            }
        }finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}

2. DataInputStream/DataOutputStream:用于读写基本数据类型,如int、double、boolean等,以便将数据写入到文件或网络。如下面的代码实例:

import java.io.*;

public class TestDataStream {
    public static void main(String[] args) throws IOException {
        try (DataOutputStream output =
                      new DataOutputStream(new FileOutputStream("temp.dat"))) {
            output.writeUTF("John");
            output.writeDouble(85.5);
            output.writeUTF("Jim");
            output.writeDouble(185.5);
            output.writeUTF("George");
            output.writeDouble(105.25);
        }

        try (DataInputStream input =
                     new DataInputStream(new FileInputStream("temp.dat"))) {
            while (true) {
                System.out.println(input.readUTF() + " " + input.readDouble());
            }
        } catch (EOFException ex) {
            System.out.println("All data were read");
        } 
    }
}

3. InputStreamReader/OutputStreamWriter:用于读写字符流,如读取文件中的字符串,以字符为单位读写文件。如下面的代码实例:

import java.io.*;

public class FileReaderWriterTest {
    public static void main(String[] args) {
        try {
            File file = new File("file.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4. ByteArrayInputStream/ByteArrayOutputStream:用于读写字节数组,一般用在序列化和反序列化对象时,可以将对象转化为字节数组,再通过字节流读写器将其写入到文件或者网络中。如下面的代码实例:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

class Student implements java.io.Serializable {
    public String name;
    public String address;
    public transient int age;
    public int phone;

    public void print() {
        System.out.println("Name=" + name);
        System.out.println("Address=" + address);
        System.out.println("Age=" + age);
        System.out.println("Phone=" + phone);
    }
}

public class SerializationDemo {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student stu = new Student();
        stu.name = "John";
        stu.address = "123 Main Street, Los Angeles, CA 90001";
        stu.age = 20;
        stu.phone = 123456;

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
        objectOutputStream.writeObject(stu);
        objectOutputStream.flush();

        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(in);
        Student stu2 = (Student) objectInputStream.readObject();
        stu2.print();
    }
}

5. Socket/ServerSocket:用于网络通信,可以在客户端和服务器之间进行数据传递,也可以实现文件传输。如下面的代码实例:

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class GreetingClient {
    public static void main(String[] args) {
        String serverName = args[0];
        int port = Integer.parseInt(args[1]);
        try {
            System.out.println("Connecting to " + serverName + " on port " + port);
            Socket client = new Socket(serverName, port);
            System.out.println("Just connected to " + client.getRemoteSocketAddress());
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);

            Scanner scanner = new Scanner(System.in);
            while (true) {
                String message = scanner.nextLine();
                out.writeUTF(message);
                if (message.equals("Bye")) break;
            }

            InputStream inFromServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            System.out.println("Server says " + in.readUTF());
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

以上是Java中IO流函数的部分常用的操作和示例。在实际开发中,我们根据需求选取不同的IO流函数,以实现我们所需的功能。