java访问Linux服务器读取文件

来源:互联网 发布:如何成为淘宝促销员 编辑:程序博客网 时间:2024/06/03 14:43
所需jar包:j2ssh-core-0.2.2.jar
java代码:
SshClient client=new SshClient();
        try{
            client.connect("此处是Linux服务器IP");
            //设置用户名和密码
            PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
            pwd.setUsername("root");
            pwd.setPassword("123456");
            int result=client.authenticate(pwd);
            if(result==AuthenticationProtocolState.COMPLETE){//如果连接完成
                System.out.println("==============="+result);
                List<SftpFile> list = client.openSftpClient().ls("/etc/mail/");
                for (SftpFile f : list) {
                    System.out.println(f.getFilename());  
                    System.out.println(f.getAbsolutePath());
                    if(f.getFilename().equals("aliases")){
                        OutputStream os = new FileOutputStream("d:/mail/"+f.getFilename());
                        client.openSftpClient().get("/etc/mail/aliases", os);
                        //以行为单位读取文件start
                        File file = new File("d:/mail/aliases");
                        BufferedReader reader = null;
                        try {
                            System.out.println("以行为单位读取文件内容,一次读一整行:");
                            reader = new BufferedReader(new FileReader(file));
                            String tempString = null;
                            int line = 1;//行号
                            //一次读入一行,直到读入null为文件结束
                            while ((tempString = reader.readLine()) != null) {
                                //显示行号
                                System.out.println("line " + line + ": " + tempString);
                                line++;
                            }
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (reader != null) {
                                try {
                                    reader.close();
                                } catch (IOException e1) {
                                }
                            }
                        }
                        //以行为单位读取文件end
                    }
                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }
0 0
原创粉丝点击