Java中的IO操作,如文件读写实例

原创 布满荆棘的人生 2024-09-26 09:00 162阅读 0赞

在Java中,IO(Input/Output)操作主要包括文件、网络等的读写。以下是一些基本的文件读写实例:

  1. 文件读取:
    ```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

  1. if (file.exists()) { // Check if the file exists
  2. try {
  3. // Using BufferedReader to read the file line by line
  4. BufferedReader reader = new BufferedReader(new FileReader(file));
  5. String line;
  6. while ((line = reader.readLine()) != null) { // Loop through each line
  7. System.out.println(line); // Print the line
  8. }
  9. reader.close(); // Close the reader
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. } else {
  14. System.out.println("File does not exist."); // If file doesn't exist
  15. }
  16. }

}

  1. 2. 文件写入:
  2. ```java
  3. import java.io.File;
  4. import java.io.IOException;
  5. public class FileWriter {
  6. public static void main(String[] args) {
  7. File file = new File("path_to_your_file.txt"); // Replace with your file path
  8. try (BufferedWriter writer = new BufferedWriter(new FileWriter(file)))) { // Using BufferedWriter for better performance when writing large amounts
  9. writer.write("This is a sample content written to the file."); // Write some sample content
  10. writer.newLine(); // Add a line break after content
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. }

注意:在运行这些示例时,请确保替换path_to_your_file.txt为实际的文件路径。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,162人围观)

还没有评论,来说两句吧...

相关阅读