Java IO流是Java中非常重要的一部分,是一個用于訪問文件、網絡等的機制。在Java IO流作業中,常見的問題是如何讀寫文件、如何處理網絡連接等。下面是一些Java IO流作業和答案的示例:
1. 如何打開一個文件并讀寫其中的內容? 下面是代碼示例: try (FileInputStream fis = new FileInputStream("file.txt"); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream("output.txt"); BufferedOutputStream bos = new BufferedOutputStream(fos)) { byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = bis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } 2. 如何讀取一個網絡連接的數據? 下面是代碼示例: try (Socket socket = new Socket("localhost", 8080); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os))) { bw.write("GET / HTTP/1.1\n"); bw.write("Host: localhost\n\n"); bw.flush(); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } 3. 如何將一個文件的內容轉換成一個字符串? 下面是代碼示例: try (FileInputStream fis = new FileInputStream("file.txt"); BufferedInputStream bis = new BufferedInputStream(fis); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = bis.read(buffer)) != -1) { baos.write(buffer, 0, bytesRead); } String content = new String(baos.toByteArray()); } catch (IOException e) { e.printStackTrace(); }
下一篇html登錄按鈕設置