以下是Java實(shí)現(xiàn)從本地拷貝圖片到服務(wù)器的步驟詳解:
1、導(dǎo)入相關(guān)庫(kù)
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.FileChannel;
2、創(chuàng)建一個(gè)方法,用于拷貝文件
public static void copyFile(String sourcePath, String targetPath) throws IOException { File sourceFile = new File(sourcePath); File targetFile = new File(targetPath); try (FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetFile); FileChannel sourceChannel = fis.getChannel(); FileChannel targetChannel = fos.getChannel()) { long transferredBytes = 0; long totalBytes = sourceChannel.size(); while (transferredBytes < totalBytes) { transferredBytes += sourceChannel.transferTo(0, totalBytes, targetChannel); } } }
3、在主方法中調(diào)用拷貝文件的方法
public static void main(String[] args) { String sourcePath = "C:/Users/username/Desktop/image.jpg"; // 本地圖片路徑 String targetPath = "/home/username/images/image.jpg"; // 服務(wù)器圖片路徑 try { copyFile(sourcePath, targetPath); System.out.println("文件拷貝成功"); } catch (IOException e) { System.out.println("文件拷貝失敗"); e.printStackTrace(); } }
注意:請(qǐng)根據(jù)實(shí)際情況修改sourcePath
和targetPath
的值。