java 输入输出ppt_Java的文件(读写)输入输出.ppt
时间: 2023-12-25 09:04:14 浏览: 69
JAVA课件Java语言输入输出系统完整版资料.ppt
Java中的文件输入输出操作可以使用Java IO库中的类来完成。下面是一些基本的示例:
1. 从文件中读取文本内容并打印到控制台:
```java
try {
BufferedReader reader = new BufferedReader(new FileReader("filename.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
```
2. 将文本内容写入文件中:
```java
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("filename.txt"));
String text = "Hello, world!";
writer.write(text);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
```
3. 从二进制文件中读取数据并打印到控制台:
```java
try {
FileInputStream inputStream = new FileInputStream("filename.bin");
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
```
4. 将数据写入二进制文件中:
```java
try {
FileOutputStream outputStream = new FileOutputStream("filename.bin");
byte[] data = { 0x01, 0x02, 0x03, 0x04 };
outputStream.write(data);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
```
这些示例只是Java IO库的基本用法,实际应用中可能需要更复杂的操作,但可以作为入门学习的起点。
阅读全文