IO操作函数:Java中常见的IO操作函数使用示例
发布时间:2023-06-13 03:56:17
Java中常见的IO操作函数包括文件操作、网络操作和输入输出流操作。
1. 文件操作
Java中常见的文件操作函数包括File类、FileInputStream类、FileOutputStream类和RandomAccessFile类,其中File类用于创建、读取和删除文件和目录,FileInputStream和FileOutputStream类用于读写文件,而RandomAccessFile类则可以读写任意位置的文件。
下面是一个使用FileInputStream类读取文件并将其内容输出到控制台的示例:
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
String line;
while ((line = dis.readLine()) != null) {
System.out.println(line);
}
fis.close();
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 网络操作
Java中常见的网络操作函数包括Socket类、ServerSocket类和URLConnection类,其中Socket类和ServerSocket类用于创建客户端和服务端的网络连接,而URLConnection类则可以连接到任何URL。
下面是一个使用Socket类实现基于TCP协议的客户端和服务器之间的通信的示例:
客户端:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 8888);
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("Hello server!");
out.flush();
socket.shutdownOutput();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("Hi client!");
out.flush();
in.close();
out.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 输入输出流操作
Java中常见的输入输出流操作函数包括InputStream类、OutputStream类、Reader类和Writer类,其中InputStream和OutputStream类用于字节流操作,而Reader和Writer类则用于字符流操作。
下面是一个使用FileWriter类写入文件的示例:
import java.io.*;
public class WriteFile {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileWriter fw = new FileWriter(file);
fw.write("Hello world!");
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上是Java常见的IO操作函数使用示例,IO操作在Java中非常常见,使用这些IO操作函数可以方便地实现文件操作、网络操作和输入输出流操作。
