Java I/O(輸入/輸出)是Java語言中用于讀取和寫入數(shù)據(jù)的標準方式。它包括File API、InputStream和OutputStream等類。Java I/O使用流(stream)的概念,即數(shù)據(jù)流的抽象表示。在流中,數(shù)據(jù)被看作是一個一維的連續(xù)數(shù)據(jù)流,通過InputStream讀取,通過OutputStream寫入。
try (BufferedReader br = new BufferedReader(new FileReader("filename.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }
Java NIO(New I/O)是Java 1.4版本中引入的一個新I/O API。它是一種基于緩沖區(qū)的I/O,提供了與標準的I/O(如Java I/O)相同或更好的性能。Java NIO通過直接緩沖區(qū)(direct buffer)訪問操作系統(tǒng)底層的數(shù)據(jù),避免了數(shù)據(jù)的二次拷貝,提高了數(shù)據(jù)傳輸?shù)男省?/p>
try (RandomAccessFile aFile = new RandomAccessFile("filename.txt", "rw")) { FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { buf.flip(); while(buf.hasRemaining()){ System.out.print((char) buf.get()); } buf.clear(); bytesRead = inChannel.read(buf); } } catch (IOException e) { e.printStackTrace(); }