在对设备节点进行操作的时候,发现读的时候进入阻塞状态(可能是设备节点异常),导致没办法继续执行后面的代码
查看了一下,文件的方式读,是没办法配置超时的自动报异常的
设计了一段代码,针对读阻塞做异常处理
public static String sendCmdToFile(String fromFile, String cmd) { byte bt[] = new byte[1024]; int c=0; AtomicBoolean isGetCode=new AtomicBoolean(false); OutputStream fosto=null; try { fosto = new FileOutputStream(fromFile); LogPrint.d("fosto.write(cmd.getBytes()) "+cmd.getBytes()); fosto.write(cmd.getBytes()); Thread mThread= new Thread(new Runnable() { @Override public void run() { FileInputStream fosfrom=null ; try { int byteLength=0; byte temp[] = new byte[100]; int len=0; fosfrom = new FileInputStream(fromFile); isGetCode.set(false); while(-1!=(len =fosfrom.read(temp))){ System.arraycopy(temp,0,bt,byteLength,len); byteLength=+len; } LogPrint.d(" fosfrom.read "+DataTypeChangeUtil.getByteBylength(bt,byteLength)); if(fosfrom!=null) { fosfrom.close(); } //Thread.sleep(50); isGetCode.set(true); } catch (ClosedByInterruptException e) { LogPrint.d(" fosfrom.read ee "+e.getMessage().toString()); if(fosfrom!=null){ try { fosfrom.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); mThread.start(); try { mThread.join(30); //等待30毫秒 if(!isGetCode.get()){ mThread.interrupt(); //如果线程阻塞,会报异常 throw new IOException(); } } catch (InterruptedException e) { e.printStackTrace(); } LogPrint.d("fosto.read(cmd.getBytes()) ok"); if(fosto!=null) { fosto.close(); } return "ok"; } catch (IOException ex) { LogPrint.d("IOException fosto "+ex.getMessage()); if(fosto!=null) { try { fosto.close(); } catch (IOException e) { e.printStackTrace(); return ""; } } return ""; } }
标签:fosto,java,read,fosfrom,IOException,io,catch,new From: https://www.cnblogs.com/baldermurphy/p/17915947.html