Java中IO流操作:FileInputStream与OutputStream的例子

原创 忘是亡心i 2024-12-10 05:24 59阅读 0赞

在Java中,FileInputStreamOutputStream是两种基本的输入输出流。以下是一些例子:

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

public class FileReader {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream(“example.txt”)) {
byte[] buffer = new byte[1024];
int read;
while ((read = fis.read(buffer))) != -1) {
// Process the bytes
System.out.print(new String(buffer, 0, read))));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

  1. 这个例子中,我们打开一个名为`example.txt`的文件,并读取其中的内容。
  2. 2. 文件写入:
  3. ```java
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. public class FileWriter {
  7. public static void main(String[] args) {
  8. try (FileOutputStream fos = new FileOutputStream("new_example.txt")) {
  9. String content = "This is a new example.";
  10. fos.write(content.getBytes());
  11. fos.flush();
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }

这个例子中,我们创建一个新的文件new_example.txt,并写入一个字符串内容。

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

发表评论

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

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

相关阅读