외부 서버 파일 Upload/Download ☕

2022-09-25·1분 읽기·

외부 서버 파일 Upload/Download ☕

외부 서버 파일 Upload/Download ☕ ■ JAVA FileDownload package remoteFileDownload; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file

외부 서버 파일 Upload/Download ☕

■ JAVA FileDownload

code
package remoteFileDownload;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
 
public class FileDownload {
 
	static String fileUrl = "https://test.com/test.txt";
	static String fileName = UUID.randomUUID().toString(); 
	static int index = fileUrl.lastIndexOf(".");
	static String ext = fileUrl.substring(index); 
 
	public static void main(String[] args) throws Exception {
		Path target = Paths.get("C:/Temp", fileName + ext);
 
		try {
			URL url = new URL(fileUrl);
			InputStream in = url.openStream();
			Files.copy(in, target); 
			in.close();
			System.out.println("File Download Success !");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

■ JAVA FileUpload

code
package remoteFileUpload;
 
import java.io.File;
import java.io.FileInputStream;
 
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
 
 
public class FileUpload{
	static String rfileName = "test2.txt";
	static String fileName = "test2.txt";
	
	public static void main(String[] args) throws Exception {
 
		try {
			String des = "/var/www/html/test"; 
 
			String src = "C:/Temp/"; 
 
			JSch jsch = new JSch();
 
			Session session = jsch.getSession("user", "192.168.xxx.xxx", 22);  
			session.setConfig("StrictHostKeyChecking", "no");
			session.setConfig("PreferredAuthentications", "password");
 
 
			session.setPassword("passowrd");  
 
			session.connect();
			Channel channel = session.openChannel("sftp");
			channel.connect();
			ChannelSftp sftpChannel = (ChannelSftp) channel;
			sftpChannel.cd(des); 
			File file = new File(src+fileName);
			FileInputStream fis = new FileInputStream(file);
			sftpChannel.put(fis, file.getName());
			fis.close();
 
			sftpChannel.disconnect();
			channel.disconnect();
			session.disconnect();   
 
			rfileName = file.getName();
			
			System.out.println(rfileName +"   Send Success !");
		} catch(Exception e) {
			e.printStackTrace();
		} 
	}
}
ShareX

이 글이 도움이 됐나요?