Java中的IO流:读写文件的常见问题及示例

原创 约定不等于承诺〃 2024-10-13 12:18 114阅读 0赞

在Java中,IO流(Input/Output Stream)是处理文件和网络数据的重要工具。以下是常见的IO流问题以及示例:

  1. 创建文件流

    • 从文件读取:FileInputStream fis = new FileInputStream("path_to_file.txt");
    • 写入文件:DataOutputStream dos = new DataOutputStream(new FileOutputStream("new_file.txt")));
  2. 处理字符流

    • 从键盘输入:BufferedReader br = new BufferedReader(new InputStreamReader(System.in))); String input = br.readLine();
    • 输出字符串:PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))))); writer.println(input);
  3. 读取和写入字节数组

    • 从文件读取:File file = new File("path_to_file.bin")); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int readCount = 0; while ((readCount = fis.read(buffer))) != -1) { // do something with the bytes }
    • 写入字节数组:byte[] data = new byte[]{1, 2, 3}}); File file = new File("path_to_file.bin")); FileOutputStream fos = new FileOutputStream(file); fos.write(data); fos.close();

以上就是Java中IO流的一些常见问题及示例,希望对你理解和使用IO流有帮助。

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

发表评论

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

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

相关阅读