2013-08-03 32 views
7

Tôi muốn lấy tệp từ hệ thống Unix đến hệ thống cục bộ của mình trên cửa sổ bằng cách sử dụng java. Tôi rất mới với khái niệm này. Bất kỳ ý tưởng về cách nó có thể được thực hiện? API java tốt nhất cho tác vụ này là gì?chuyển các tệp từ Unix sang cửa sổ bằng cách sử dụng java

+0

Bạn có thể giải thích lý do bạn muốn sử dụng Java cụ thể không? Samba hoặc SFTP đang làm việc, các tùy chọn sẵn sàng để cài đặt đã thực hiện việc này. – chrylis

Trả lời

4

Tôi đã tìm thấy JSch là lời đề nghị rất hữu ích và thẳng thắn. Dưới đây là một đoạn mã được viết để đặt tất cả các tệp .txt trong một thư mục đã cho trên máy chủ sftp.

public static void sftpConnection() { 

    // Object Declaration. 
    JSch jsch = new JSch(); 
    Session session = null; 
    Channel channel = null; 

    // Variable Declaration. 
    String user = "foo"; 
    String host = "10.9.8.7"; 
    Integer port = 22; 
    String password = "test123"; 
    String watchFolder = "\\localhost\textfiles"; 
    String outputDir = "/remote/textFolder/"; 
    String filemask = "*.txt"; 


    try { 
     session = jsch.getSession(user, host, port); 

     /* 
     * StrictHostKeyChecking Indicates what to do if the server's host 
     * key changed or the server is unknown. One of yes (refuse connection), 
     * ask (ask the user whether to add/change the key) and no 
     * (always insert the new key). 
     */ 
     session.setConfig("StrictHostKeyChecking", "no"); 
     session.setPassword(password); 

     session.connect(); 

     channel = session.openChannel("sftp"); 
     channel.connect(); 
     ChannelSftp sftpChannel = (ChannelSftp)channel; 

     // Go through watch folder looking for files. 
     File[] files = findFile(watchFolder, filemask); 
     for(File file : files) { 
      // Upload file. 
      putFile(file, sftpChannel, outputDir);    
     }     
    } finally { 
     sftpChannel.exit(); 
     session.disconnect(); 
    } 
} 

public static void putFile(File file, ChannelSftp sftpChannel, String outputDir) { 

    FileInputStream fis = null; 

    try { 
     // Change to output directory. 
     sftpChannel.cd(outputDir); 

     // Upload file. 

     fis = new FileInputStream(file); 
     sftpChannel.put(fis, file.getName()); 
     fis.close(); 

    } catch{} 
} 

public static File[] findFile(String dirName, final String mask) { 
    File dir = new File(dirName); 

    return dir.listFiles(new FilenameFilter() { 
     public boolean accept(File dir, String filename) 
      { return filename.endsWith(mask); } 
    }); 
} 
+1

Cảm ơn bạn rất nhiều – user1585111

2

Điều đầu tiên trong tâm trí của tôi là FTP.

+1

nhưng FTP là không an toàn, tôi nghĩ rằng nó sẽ là tốt nếu chúng ta tiếp tục với sftp. – user1585111

2

Có nhiều lựa chọn để thực hiện điều đó. Đầu tiên một giao tiếp socket đơn giản giữa một máy khách java và một máy chủ. Nếu bạn muốn đi với phương pháp này sau đó làm theo này:

http://mrbool.com/file-transfer-between-2-computers-with-java/24516

Sau đó, có giao thức cấp cao hiện thực khác có thể được sử dụng như FTP, HTTP, vv

theo một SO liên quan gửi cho máy chủ ứng dụng khách java FTP: FTP client server model for file transfer in Java

+0

cảm ơn bạn, có một số thông tin tốt .. có bất kỳ api java nào để làm những điều này khá đơn giản không? – user1585111

+0

@ user1585111 java apis có sẵn và được sử dụng rộng rãi cho giao tiếp socket. kiểm tra này: http://download.oracle.com/javase/tutorial/networking/sockets/ –

+0

jsch có thể giúp tôi để đạt được nhiệm vụ này? – user1585111

9

Nếu máy Unix hỗ trợ SFTP, JSch là một tùy chọn. Bạn có thể điều chỉnh mã sau để đáp ứng nhu cầu của mình:

private static final String USER_PROMPT = "Enter [email protected]:port"; 
private static final boolean USE_GUI = true; 

public static void main(final String[] arg) { 
    Session session = null; 
    ChannelSftp channelSftp = null; 
    try { 
    final JSch jsch = new JSch(); 

    final String defaultInput = System.getProperty("user.name") + "@localhost:22"; 
    String input = (USE_GUI) ? JOptionPane.showInputDialog(USER_PROMPT, defaultInput) : System.console().readLine("%s (%s): ", USER_PROMPT, defaultInput); 
    if (input == null || input.trim().length() == 0) { 
     input = defaultInput; 
    } 
    final int indexOfAt = input.indexOf('@'); 
    final int indexOfColon = input.indexOf(':'); 
    final String user = input.substring(0, indexOfAt); 
    final String host = input.substring(indexOfAt + 1, indexOfColon); 
    final int port = Integer.parseInt(input.substring(indexOfColon + 1)); 

    jsch.setKnownHosts("/path/to/known_hosts"); 
    // if you have set up authorized_keys on the server, using that identitiy 
    // with the code on the next line allows for password-free, trusted connections 
    // jsch.addIdentity("/path/to/id_rsa", "id_rsa_password"); 

    session = jsch.getSession(user, host, 22); 

    final UserInfo ui = new MyUserInfo(); 
    session.setUserInfo(ui); 
    session.connect(); 
    channelSftp = (ChannelSftp) session.openChannel("sftp"); 
    channelSftp.connect(); 
    channelSftp.get("/remotepath/remotefile.txt", "/localpath/localfile.txt"); 
    } finally { 
    if (channelSftp != null) { 
     channelSftp.exit(); 
    } 
    if (session != null) { 
     session.disconnect(); 
    } 
    } 
} 

public static class MyUserInfo implements UserInfo { 
    private String password; 

    @Override 
    public String getPassword() { 
    return password; 
    } 

    @Override 
    public boolean promptYesNo(final String str) { 
    final Object[] options = {"yes", "no"}; 
    final boolean yesNo = (USE_GUI) ? JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]) == 0 : System.console().readLine("Enter y or n: ").equals("y"); 
    return yesNo; 
    } 

    @Override 
    public String getPassphrase() { 
    return null; 
    } 

    @Override 
    public boolean promptPassphrase(final String message) { 
    return true; 
    } 

    @Override 
    public boolean promptPassword(final String message) { 
    if (!USE_GUI) { 
     password = new String(System.console().readPassword("Password: ")); 
     return true; 
    } else { 
     final JTextField passwordField = new JPasswordField(20); 
     final Object[] ob = {passwordField}; 
     final int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); 
     if (result == JOptionPane.OK_OPTION) { 
     password = passwordField.getText(); 
     return true; 
     } else { 
     return false; 
     } 
    } 
    } 

    @Override 
    public void showMessage(final String message) { 
    if (!USE_GUI) { 
     System.console().printf(message); 
    } else { 
     JOptionPane.showMessageDialog(null, message); 
    } 
    } 
} 
+0

Cảm ơn bạn rất nhiều – user1585111

+0

Cách sử dụng độc đáo và rất thanh lịch. –

+0

channelSftp.get ("/ remotepath/remotefile.txt", "/localpath/localfile.txt"); đặc biệt hữu ích – parishodak

Các vấn đề liên quan