Java中的IO流:读写文件的常见问题及示例
在Java中,IO流(Input/Output Stream)是处理文件和网络数据的重要工具。以下是常见的IO流问题以及示例:
创建文件流:
- 从文件读取:
FileInputStream fis = new FileInputStream("path_to_file.txt");
- 写入文件:
DataOutputStream dos = new DataOutputStream(new FileOutputStream("new_file.txt")));
- 从文件读取:
处理字符流:
- 从键盘输入:
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);
- 从键盘输入:
读取和写入字节数组:
- 从文件读取:
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流有帮助。
还没有评论,来说两句吧...