java获取指定文件路径吗,如何在Java中指定文件路径?

I have created a java application for "Debian Linux." Now I want that that application reads a file placed in the directory where the jar file of that application is specified. So what to specify at the argument of the File Object?

File fileToBeReaded = new File(...);

What to specify as argument for the above statement to specify relative filepath representing the path where the jar file of the application has been placed?

解决方案

If you know the name of the file, of course it's simply

new File("./myFileName")

If you don't know the name, you can use the File object's list() method to get a list of files in the current directory, and then pick the one you want.

如果你想在 Java 指定窗口路径下的文件进行压缩,你可以使用 Java 的 ZipOutputStream 类来进行文件的压缩。以下是一个示例代码指定了一个窗口路径,将该路径下的所有文件文件夹压缩为一个 ZIP 文件: ```java import java.io.*; import java.util.zip.*; import javax.swing.*; public class ZipFolder { public static void main(String[] args) throws Exception { // 弹出文件选择对话框,让用户选择要压缩的文件夹 JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result = chooser.showOpenDialog(null); if (result != JFileChooser.APPROVE_OPTION) { return; } // 获取用户选择的文件路径 String sourceFolderPath = chooser.getSelectedFile().getPath(); String zipFilePath = sourceFolderPath + ".zip"; // 目标 ZIP 文件路径 FileOutputStream fos = new FileOutputStream(zipFilePath); ZipOutputStream zos = new ZipOutputStream(fos); File sourceFolder = new File(sourceFolderPath); addFolderToZip("", sourceFolder, zos); zos.close(); fos.close(); } private static void addFolderToZip(String parentPath, File folder, ZipOutputStream zos) throws Exception { String folderPath = parentPath + folder.getName() + "/"; zos.putNextEntry(new ZipEntry(folderPath)); for (File file : folder.listFiles()) { if (file.isDirectory()) { addFolderToZip(folderPath, file, zos); } else { FileInputStream fis = new FileInputStream(file); zos.putNextEntry(new ZipEntry(folderPath + file.getName())); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } fis.close(); } } } } ``` 在这个示例代码,我们使用了 Java 的 Swing 组件 JFileChooser 创建了一个文件选择对话框,让用户选择要压缩的文件夹。然后,我们获取用户选择的文件路径,将该路径下的所有文件文件夹压缩为一个 ZIP 文件。最后,我们将压缩后的文件保存在原始文件路径下,文件名为原始文件夹名加上 `.zip` 后缀。运行该程序,你会看到一个文件选择对话框,选择要压缩的文件夹后,程序会自动将其压缩为一个 ZIP 文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值