Java API使用疑问:IO流操作与文件读写示例
在Java中,IO流(Input/Output Stream)主要用来处理数据的输入输出。以下是一些基础的IO流操作和文件读写的示例:
- 创建并使用InputStream:
```java
import java.io.FileInputStream;
import java.io.IOException;
public class InputStreamExample {
public static void main(String[] args) {
// 创建FileInputStream对象,参数为文件路径
FileInputStream fis = new FileInputStream(“example.txt”);
try {
// 使用read()方法读取数据,返回值是字节数
byte data = fis.read();
System.out.println("Read byte: " + data);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2. **创建并使用FileWriter**:
```java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String[] args) {
// 创建FileWriter对象,参数为文件路径和字符编码
FileWriter fw = new FileWriter("example.txt", "UTF-8"));
try {
// 使用write()方法写入数据,参数为要写入的字符串
fw.write("Hello, World!\n");
System.out.println("Data written successfully");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
以上示例中,InputStreamExample
展示了如何读取文件的一部分数据,而FileWriterExample
演示了如何写入新的数据到文件。
还没有评论,来说两句吧...