理解和实践Java中IO流操作实例展示
在Java中,IO流主要是用来处理输入和输出的,包括文件、网络等。以下是一些.IO流操作的实际例子:
- 读取文件内容:
```java
import java.io.*;
public class FileRead {
public static void main(String[] args) {
String fileName = “example.txt”; // 文件名
try (BufferedReader br = new BufferedReader(new FileReader(fileName)))) {
System.out.println(“File Content: \n” + br.readLine()); // 读取第一行内容
while ((br.readLine()) != null)) { // 遍历文件,直到读取到空行
System.out.println(br.readLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println(“File Not Found: “ + fileName);
}
}
}
2. **写入文件内容**:
```java
import java.io.*;
public class FileWriter {
public static void main(String[] args) {
String fileName = "example.txt"; // 文件名
String content = "Hello, World!"; // 内容
try (PrintWriter writer = new PrintWriter(new FileWriter(fileName)))) {
writer.println(content);
System.out.println("Content written to file: " + content);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error writing to file: " + fileName);
}
}
}
以上就是Java中IO流操作的一些实例展示。
还没有评论,来说两句吧...