Java讀取Linux上檔案
阿新 • • 發佈:2018-11-07
public void readFile() { //建立遠端連線,預設連線埠為22,如果不使用預設,可以使用方法 //new Connection(ip, port)建立物件 String ip = ""; String usr = ""; String pwd = ""; //int port=22; Connection conn = null; String date = ""; String path=""; try { //連線遠端伺服器 // 連線部署伺服器 conn = new Connection(ip); conn.connect(); //使用使用者名稱和密碼登入 boolean b = conn.authenticateWithPassword(usr, pwd); if (!b) { throw new IOException("Authentication failed."); } else { SFTPv3Client sft = new SFTPv3Client(conn); Vector<?> v = sft.ls("path"); for (int i = 0; i < v.size(); i++) { SFTPv3DirectoryEntry s = new SFTPv3DirectoryEntry(); s = (SFTPv3DirectoryEntry) v.get(i); //檔名 String filename = s.filename; if (filename.length() > 17) { String substring = filename.substring(7, 17); if (substring.equals(date)) { System.out.println(filename); Session ss=null; ss=conn.openSession(); ss.execCommand("cat ".concat("path"+filename)); InputStream is = new StreamGobbler(ss.getStdout()); BufferedReader bs = new BufferedReader(new InputStreamReader(is)); while(true){ String line = bs.readLine(); if(line==null){ break; }else{ System.out.println("abc........................"+line); } } bs.close(); ss.close(); conn.close(); } } } } } catch (IOException e) { System.err.printf("使用者%s密碼%s登入伺服器%s失敗!", usr, pwd, ip); e.printStackTrace(); } }