本文共 2292 字,大约阅读时间需要 7 分钟。
Java IO系统提供了丰富的类来处理字符和字节的读写操作,这些类按照功能和目的可以分为字节流和字符流。了解它们的区别和适用场景是编程时的关键。
输入:
FileInputStream
:读取文件。ByteArrayInputStream
:读取字节数组。BufferedInputStream
:提供缓冲,提高读取速度。PushbackInputStream
:允许回退。输出:
FileOutputStream
:写入文件。ByteArrayOutputStream
:写入字节数组。BufferedOutputStream
:提供缓冲,提高写入速度。转换:
InputStreamReader
:从字节流读取字符流。OutputStreamWriter
:将字符流转为字节流。输入:
FileReader
:读取字符文件。StringReader
:读取字符串。BufferedReader
:提供缓冲,处理大量字符。输出:
FileWriter
:写入字符文件。StringWriter
:写入字符串缓冲区。BufferedWriter
:提供缓冲,提高写入效率。public class BrAndBwOrPw { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("demo\\test.txt"))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("demo\\test2.txt"))); PrintWriter pw = new PrintWriter("demo\\test3.txt"); String s; while ((s = br.readLine()) != null) { System.out.println(s); bw.write(s); bw.newLine(); pw.println(s); } bw.flush(); br.close(); bw.close(); pw.flush(); pw.close(); }}
用于随机访问文件,定位到特定位置读写大对象。例如:
public class RafDemo { public static void main(String[] args) throws IOException { File file = new File("demo", "rafTest.bin"); if (!file.exists()) { file.createNewFile(); } RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); byte[] data = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}; raf.write(data); raf.writeInt(0x12345678); byte[] read_data = new byte[4]; raf.read(read_data); System.out.println("Read: " + String.valueOf(read_data)); raf.close(); }}
选择合适的IO流类是编程中的关键。理解字节流和字符流的区别,正确使用编码转换和缓冲流,可以提高程序的性能和稳定性。复杂的应用场景可以考虑使用RandomAccessFile或其他高级IO流,确保数据读写的准确性和效率。
转载地址:http://ixflz.baihongyu.com/