Java中的IO操作,如文件读写实例
在Java中,IO(Input/Output)操作主要包括文件、网络等的读写。以下是一些基本的文件读写实例:
- 文件读取:
```java
import java.io.File;
import java.io.IOException;
public class FileReader {
public static void main(String[] args) {
File file = new File(“path_to_your_file.txt”); // Replace with your file path
if (file.exists()) { // Check if the file exists
try {
// Using BufferedReader to read the file line by line
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) { // Loop through each line
System.out.println(line); // Print the line
}
reader.close(); // Close the reader
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("File does not exist."); // If file doesn't exist
}
}
}
2. 文件写入:
```java
import java.io.File;
import java.io.IOException;
public class FileWriter {
public static void main(String[] args) {
File file = new File("path_to_your_file.txt"); // Replace with your file path
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file)))) { // Using BufferedWriter for better performance when writing large amounts
writer.write("This is a sample content written to the file."); // Write some sample content
writer.newLine(); // Add a line break after content
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意:在运行这些示例时,请确保替换path_to_your_file.txt
为实际的文件路径。
还没有评论,来说两句吧...