Java是一種非常流行的編程語言,用于開發(fā)各種不同類型的應(yīng)用程序,包括桌面應(yīng)用程序、Web應(yīng)用程序和移動(dòng)應(yīng)用程序。在這些應(yīng)用程序中,輸入輸出(IO)和新輸入輸出(NIO)是非常重要的概念,因?yàn)樗麄儙椭绦驈耐獠凯h(huán)境中讀取和寫入數(shù)據(jù)。
Java IO在處理文件、網(wǎng)絡(luò)和流時(shí)非常有用。例如,可以使用FileReader、FileWriter、BufferedReader和BufferedWriter等類來讀取和寫入文件。以下是一個(gè)簡單的IO代碼示例,它從文件中讀取每一行字符串,并將這些字符串寫入另一個(gè)文件中:
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt")); BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) { String line; while ((line = reader.readLine()) != null) { writer.write(line); writer.newLine(); } } catch (IOException e) { e.printStackTrace(); }
Java NIO是Java 1.4引入的新特性。它引入了許多新的類,如ByteBuffer、Selector和Channel。NIO提供了比IO更高效、更靈活的處理方式。下面是一個(gè)簡單的NIO代碼示例,它從SocketChannel中讀取數(shù)據(jù),并將這些數(shù)據(jù)立即發(fā)送回給客戶端:
try (Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open()) { serverSocket.bind(new InetSocketAddress("localhost", 8080)); serverSocket.configureBlocking(false); serverSocket.register(selector, serverSocket.validOps()); while (true) { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isAcceptable()) { SocketChannel client = serverSocket.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { SocketChannel client = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); client.read(buffer); buffer.flip(); client.write(buffer); buffer.clear(); client.close(); } iterator.remove(); } } } catch (IOException e) { e.printStackTrace(); }