從具有超時的輸入流中讀取
特定問題需要量身定制的解決方案。本題旨在建構一個方法,在給定的時間限制內從 InputStream 中檢索數據,如果超過則優雅地失敗並顯示錯誤代碼。
Java InputStream 的具體注意事項
解決此問題需要理解Java的InputStream類:
- 它的read()方法不能通用
- 將InputStream 包裝到Reader 或InterruptibleChannel 類別中不會擴充可用選項。
- available() 可能隨時回傳 0。
- close() 可能會阻塞或什麼都不做。
- 無條件終止另一個執行緒不是
使用available() 檢查輸入可用性
與問題陳述中的說法相反,InputStream.available() 並不總是返回0。它提供了一個容易的估計可用資料無阻塞。但是,它可能會低估真實的數據計數。
最基本的解決方案
這種簡單的方法不會施加任何阻塞或超時約束:
byte[] inputData = new byte[1024]; int result = is.read(inputData, 0, is.available());
超時感知解決方案
為了進行更精細的控制,方法可以在指定的範圍內用可用資料填充緩衝區timeout:
public static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis) throws IOException { int bufferOffset = 0; long maxTimeMillis = System.currentTimeMillis() + timeoutMillis; while (System.currentTimeMillis() <h3 id="解決方案利用率">解決方案利用率</h3><pre class="brush:php;toolbar:false">byte[] inputData = new byte[1024]; int readCount = readInputStreamWithTimeout(System.in, inputData, 6000); // 6 second timeout
這提供了一種從InputStream 讀取阻塞和非阻塞輸入來源的逾時的方法。
以上是如何從具有逾時的 Java 輸入流讀取資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Java是平台獨立的,因為其"一次編寫,到處運行"的設計理念,依賴於Java虛擬機(JVM)和字節碼。 1)Java代碼編譯成字節碼,由JVM解釋或即時編譯在本地運行。 2)需要注意庫依賴、性能差異和環境配置。 3)使用標準庫、跨平台測試和版本管理是確保平台獨立性的最佳實踐。

Java'splatFormIndenceIsnotsimple; itinvolvesComplexities.1)jvmcompatiblemustbebeeniblemustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

thejvmistheruntimeenvorment forexecutingjavabytecode,Cocucialforjava的“ WriteOnce,RunanyWhere”能力

JavaremainsatopchoicefordevelopersduetoitsplatFormentence,對象與方向設計,強度,自動化的MememoryManagement和ComprechensivestAndArdArdArdLibrary

Java'splatFormIndependecemeansDeveloperScanWriteCeandeCeandOnanyDeviceWithouTrecompOlding.thisAcachivedThroughThroughTheroughThejavavirtualmachine(JVM),WhaterslatesbyTecodeDecodeOdeIntComenthendions,允許univerniverSaliversalComplatibilityAcrossplatss.allospplats.s.howevss.howev

要設置JVM,需按以下步驟進行:1)下載並安裝JDK,2)設置環境變量,3)驗證安裝,4)設置IDE,5)測試運行程序。設置JVM不僅僅是讓其工作,還包括優化內存分配、垃圾收集、性能調優和錯誤處理,以確保最佳運行效果。

toensurejavaplatFormIntence,lofterTheSeSteps:1)compileAndRunyOpplicationOnmultPlatFormSusiseDifferenToSandjvmversions.2)upureizeci/cdppipipelinelikeinkinslikejenkinsorgithikejenkinsorgithikejenkinsorgithikejenkinsorgithike forautomatecross-plateftestesteftestesting.3)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3 Linux新版
SublimeText3 Linux最新版

Dreamweaver CS6
視覺化網頁開發工具