java gets the code for a known file extension
- 2020-06-12 09:04:04
- OfStack
1. Demand analysis
1, get known file extensions -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - "to read the file first, get the file name
2, abc.txt extension is txt, abc.Java
2. Technical Difficulties
1. Convert 1 given path into 1 file object and get the complete file name
You can do this directly with the new File() class, and then get the file name from getName
2. How to get the extension through the file name?
This can be obtained by splitting the file names into regular expressions
Code implementation :(PS adds a function that gives the file extension under the specified directory to get the loop directory)
package com.itheima;
import java.io.File;
/**
* 7 , Write a program to get the extension of a known file . Pay attention to : abc.txt The extension is txt, abc.java.txt The extension is also txt.
*
* @author 281167413@qq.com
*/
public class Test7 {
public static void main(String[] args) {
String srcPath = "D:/java/java.copy.doc";
getFilenameExtension(srcPath);
}
// Gets the extension of the specified file
public static void getFilenameExtension(String srcPath) {
// Converts the source path to a file object
File file = new File(srcPath);
if (file.isFile()) {
String name = file.getName();
String[] exName = name.split("\\.");
System.out.println(exName[exName.length - 1]);
} else {
System.out.println("It's not a file!");
}
}
// Gets the extension of the file in the specified directory
public static void getDirFilenameExtension(String srcPath) {
// Converts the source path to the directory object
File[] file = (new File(srcPath)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isDirectory()) {
// Source folder ready to be copied
srcPath = srcPath + "/" + file[i].getName();
getDirFilenameExtension(srcPath);
} else {
// The source file
File sourceFile = file[i];
// The file name
String name = sourceFile.getName();
String[] exName = name.split("\\.");
System.out.println(exName[exName.length - 1]);
}
}
}
}
For more details, please refer to previous articles published on this site.