获取文件路径

package File;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JLabel;

//构造函数实现具体文件选择,获取文件所在路径
public class FileChooser {

    String Str = new String();
    String Str1 = new String();
    String Str2 = new String();

    public String actionPerformed() {
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        jfc.showDialog(new JLabel(), "选择");
        File file = jfc.getSelectedFile();
        if (file==null){
            return null;
        }
        if (file.isDirectory()) {
            Str1 = file.getAbsolutePath();
        } else if (file.isFile()) {
            Str1 = file.getAbsolutePath();
        }
        Str = jfc.getSelectedFile().getName(); //System.out.println("文件名:"+Str);
        String[] S = Str1.split("\\\\");//因为字符串里的\\ 到了split里,需要分别转义,那么自然就需要用\\ \\来表示了,也就是\\\\
        int j = S.length;
        for (int i = 0; i < S.length - 1; i++) {
            Str2 += S[i] + "/";
        }
        Str2 += S[j - 1];
        System.out.println("处理结果:" + Str2);
        return Str2;
    }

    private boolean isDirectory() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private String getAbsolutePath() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private boolean isFile() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Jupyter中读取文件路径,可以通过使用Python的内置库——'os'模块来构建路径。下面是一些常见的方法: 1. 使用绝对路径:如果您已经知道要读取的文件的绝对路径,可以直接将其作为字符串输入。 例如,如果文件位于'C:/Users/Username/Desktop/file.txt',您可以使用以下代码读取该文件: ```python file_path = 'C:/Users/Username/Desktop/file.txt' with open(file_path, 'r') as file: # 处理文件 ``` 2. 使用相对路径:相对路径是相对于当前Jupyter笔记本所在的目录。这种方法更加灵活,因为它不依赖于特定的文件系统路径。 例如,如果文件与Jupyter笔记本位于同一目录下,可以直接使用文件名来读取该文件: ```python file_path = 'file.txt' with open(file_path, 'r') as file: # 处理文件 ``` 或者,如果文件位于Jupyter笔记本所在目录的子目录中,可以使用相对路径来读取文件: ```python file_path = 'subdirectory/file.txt' with open(file_path, 'r') as file: # 处理文件 ``` 3. 使用os模块:os模块提供了一种跨平台的方法来获取文件路径。可以使用`os.path.join()`函数将目录路径文件名组合起来,并使用`os.getcwd()`函数获取当前工作目录。 例如,假设文件位于当前工作目录的子目录中,可以使用以下代码读取文件: ```python import os file_path = os.path.join(os.getcwd(), 'subdirectory', 'file.txt') with open(file_path, 'r') as file: # 处理文件 ``` 以上是读取文件路径的几种常见方法,您可以根据实际情况选择合适的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值