Java的IO流操作:文件读写示例

原创 水深无声 2024-12-01 07:12 109阅读 0赞

在Java中,我们可以使用io包中的类来实现文件的读写。以下是一些基本的示例:

  1. 文件读取:
    ```java
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;

public class ReadFile {
public static void main(String[] args) {
File file = new File(“path_to_your_file.txt”); // Replace with your file path

  1. try (FileInputStream fis = new FileInputStream(file)) {
  2. byte[] buffer = new byte[1024]; // Change the size as per requirement
  3. while (true) {
  4. int readBytes = fis.read(buffer);
  5. if (readBytes == -1) { // Break condition for end of file
  6. break;
  7. }
  8. System.out.println(new String(buffer, 0, readBytes))));
  9. }
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. }

}

  1. 2. 文件写入:
  2. ```java
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. public class WriteFile {
  7. public static void main(String[] args) {
  8. File file = new File("path_to_your_file.txt"); // Replace with your file path
  9. try (FileWriter writer = new FileWriter(file)) {
  10. writer.write("Hello, World! \n This is a sample text."); // Your data to be written
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. }

以上代码示例分别展示了如何读取文件和如何写入文件。请根据你的实际需求替换路径和内容。

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

发表评论

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

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

相关阅读