1. 文件上传
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class FileUpload {
public static void main(String[] args) {
File source = new File("/path/to/source/file");
File dest = new File("/path/to/destination/file");
try {
FileUtils.copyFile(source, dest);
System.out.println("File uploaded successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 文件下载
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class FileDownload {
public static void main(String[] args) {
String url = "https://example.com/file-to-download.txt";
String fileName = "file-to-download.txt";
try {
URL website = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(fileName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
System.out.println("File downloaded successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 文件压缩
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileCompression {
public static void main(String[] args) {
File source = new File("/path/to/source/file");
File dest = new File("/path/to/destination/file.zip");
try {
FileOutputStream fos = new FileOutputStream(dest);
ZipOutputStream zos = new ZipOutputStream(fos);
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(source);
zos.putNextEntry(new ZipEntry(source.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
zos.close();
System.out.println("File compressed successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. 文件转PDF
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileToPdf {
public static void main(String[] args) {
File source = new File("/path/to/source/file");
File dest = new File("/path/to/destination/file.pdf");
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
FileInputStream fis = new FileInputStream(source);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
document.add(new com.itextpdf.text.Paragraph(new String(buffer, 0, length)));
}
document.close();
fis.close();
System.out.println("File converted to PDF successfully!");
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
}
Q.E.D.