Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中删除部分文件扩展名_Java - Fatal编程技术网

在java中删除部分文件扩展名

在java中删除部分文件扩展名,java,Java,我想删除java中文件扩展名的一部分,以便只选择实际的txt文件名。我有一个文件对话框来浏览文件,然后选定的文件存储在一个变量中 // take chosen f name. chosen_f_name = txtFile.getText(); System.out.println(chosen_f_name); 哪个输出 C:\Users\username\Documents\Project\projectname\data_file.txt 如何使用声明为仅获取数据文件.

我想删除java中文件扩展名的一部分,以便只选择实际的txt文件名。我有一个文件对话框来浏览文件,然后选定的文件存储在一个变量中

  // take chosen f name.
  chosen_f_name = txtFile.getText();
  System.out.println(chosen_f_name);
哪个输出

  C:\Users\username\Documents\Project\projectname\data_file.txt
如何使用声明为仅获取
数据文件.txt
部分的所选\u f\u name变量删除之前的所有内容,包括最后一个
\

字符串结果\u name=selected\u name.substring(selected\u name.lastIndexOf(file.separatorChar)+1);

您可以按如下方式执行:

import java.io.File;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        String chosen_f_name = "C:\\Users\\username\\Documents\\Project\\projectname\\data_file.txt";
        System.out.println(chosen_f_name);
        String fileName = chosen_f_name.substring(chosen_f_name.lastIndexOf("\\") + 1);
        System.out.println(fileName);

        // Alternatively, you can use File.separator to avoid hard coded platform
        // dependent separator e.g.
        URL location = Main.class.getProtectionDomain().getCodeSource().getLocation();
        String file = location.getFile()+"Main.java";
        System.out.println(file);
        String fName = file.substring(file.lastIndexOf(File.separator) + 1);
        System.out.println(fName);
    }
}
输出:

C:\Users\username\Documents\Project\projectname\data_file.txt
data_file.txt
/Users/arvind.avinash/Documents/workspace-spring-tool-suite-4-4.4.0.RELEASE/AdHoc/bin/Main.java
Main.java

什么类型的
txtFile
以及如何使用
FileDialog
?我可能会使用。另外,不要硬编码反斜杠作为分隔符,这会使程序平台不受影响。使用
File.separator
代替。简单、有效、跨平台、初学者友好:完美!