Java中的IO(Input/Output)是Java编程语言中用于处理输入和输出操作的一部分。它允许Java程序与外部世界(如文件、网络等)进行交互。Java IO主要包括字节流和字符流两种形式。
字节流是以字节为单位进行数据处理的流,主要包括InputStream
和OutputStream
两个抽象类。InputStream
类的子类用于从程序中读取输入数据,而OutputStream
类的子类则用于向程序中输出数据。这些类都是基于字节进行操作的,因此适合处理二进制数据。
字符流则是以字符为单位进行数据处理的流,主要包括Reader
和Writer
两个抽象类。Reader
类的子类用于从程序中读取字符数据,而Writer
类的子类则用于向程序中输出字符数据。这些类是基于字符进行操作的,因此适合处理文本数据。
在Java IO中,还提供了许多具体的实现类,如FileInputStream
、FileOutputStream
、BufferedReader
、BufferedWriter
等,用于处理不同类型的输入输出操作。例如,FileInputStream
和FileOutputStream
类可以用于读写二进制文件,而BufferedReader
和BufferedWriter
类则可以用于高效地读写文本文件。
此外,Java IO还提供了许多用于文件操作的类,如File
类,它提供了创建、删除、重命名和复制文件等方法。
在使用Java IO时,需要注意一些常见问题,如文件路径错误和文件未找到异常等。为了避免这些问题,需要确保指定的文件路径是正确的,并检查文件是否存在。
字节流示例
读取文件(字节流)
import java.io.*;
public class ByteStreamReader {
public static void main(String[] args) {
File file = new File("example.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
String data = new String(buffer, 0, bytesRead);
System.out.print(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
写入文件(字节流)
import java.io.*;
public class ByteStreamWriter {
public static void main(String[] args) {
File file = new File("output.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
String data = "Hello, World!";
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
字符流示例
读取文件(字符流)
import java.io.*;
public class CharacterStreamReader {
public static void main(String[] args) {
File file = new File("example.txt");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
写入文件(字符流)
import java.io.*;
public class CharacterStreamWriter {
public static void main(String[] args) {
File file = new File("output.txt");
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(file));
String data = "Hello, World!";
bw.write(data);
bw.newLine(); // 写入一个新行
bw.write("This is another line.");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}