Java 文件名操作的相关工具类 & Java中windows路径转换成linux路径等工具类

发布时间:2022-06-27 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Java 文件名操作的相关工具类 & Java中windows路径转换成linux路径等工具类脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Java 文件名操作的相关工具类

 

  1 import java.io.File;
  2 import java.util.regex.Matcher;
  3 import java.util.regex.Pattern;
  4 
  5 public class FileNameUtil {
  6     /**
  7      * 修改指定文件的扩展名
  8      * @param fileName
  9      * @param newExt
 10      * @return
 11      */
 12     public static String changeFileExt(String fileName, String newExt){
 13         return fileName.replaceAll("\.[^\.\\/]*$", "") + "." + newExt.replaceAll("^\.", "");
 14     }
 15     /**
 16      * 去掉文件的扩展名
 17      * @param fileName
 18      * @return
 19      */
 20     public static String removeFileExt(String fileName){
 21         return fileName.replaceAll("\.[^\\/\.]*$", "");
 22     }
 23     
 24     /**
 25      * 修正文件名错误,主要包括出现/的、双\的 
 26      * @param fileName
 27      * @return
 28      */
 29     public static String correctFileName(String fileName){
 30         return fileName.replaceAll("(?!^)[\\/]+", "\\");
 31     }
 32     /**
 33      * 修正文件名错误,主要包括出现/的、双\的 成为linux 
 34      * @param fileName
 35      * @return
 36      */
 37     public static String correctFileName4Linux(String fileName){
 38         return fileName.replaceAll("(?!^)[\\/]+", "/");
 39     }
 40     
 41     /**
 42      * 判断文件是否存在 
 43      * @param fileName
 44      * @return
 45      */
 46     public static boolean isFileExists(String fileName){
 47         //把一个或多个或/替换成1个
 48         File f = new File(correctFileName(fileName));
 49         try{
 50             return f.exists();
 51         }finally{
 52             f = null;
 53         }
 54     }
 55     
 56     /**
 57      * 连接两个文件名
 58      * @param base
 59      * @param addITion
 60      * @return
 61      */
 62     public static String fileNameAdd(String base, String addition){
 63         return base.replaceAll("[\\/]+$", "") + "\" + addition.replaceAll("^[\\/]+", "");
 64     }
 65     
 66     /**
 67      * 是不是UNC路径 
 68      * @param fileName
 69      * @return
 70      */
 71     public static boolean isUNC(String fileName){
 72         return fileName.matches("^\\{2}[^\\/]+\\[\s\S]*$");
 73     }
 74     
 75     /**
 76      * 获取文件名的扩展名 
 77      * @param fileName
 78      * @return
 79      */
 80     public static String extractFileExt(String fileName){
 81         Pattern p = Pattern.COMpile("\.[^\\/.]+$");
 82         Matcher m = p.matcher(fileName);
 83         return m.find()? m.group() : "";
 84     }
 85     
 86     /**
 87      * 获取文件的路径(最后的会被去掉) 
 88      * @param fileName
 89      * @return
 90      */
 91     public static String extractFilePath(String fileName){
 92         return fileName.replaceAll("[\\/][^\\/]*$", "");
 93     }
 94     
 95     /**
 96      * 获取文件绝对路径的文件名部分 
 97      * @param fileName
 98      * @return
 99      */
100     public static String extractFileName(String fileName){
101         return fileName.replaceAll("^[\s\S]*[\\/]", "");
102     }
103     
104     /**
105      * 获取相对路径(去掉盘符或UNC的主机)
106      * @param fileName
107      * @return
108      */
109     public static String extractRelativePath(String fileName){
110         if(isUNC(fileName)){
111             return fileName.replaceAll("^\\{2}[^\\/]+[\\/]+", "");
112         }else{
113             return fileName.replaceAll("^.*\:\\+", "");
114         }
115     }
116     
117     /**
118      * 把盘符 和 文件路径拼接起来 得到完整的文件地址,自动判断拼接的时候前面是不是有  斜杠 
119      * @param driverOrLpath windows系统下的盘符,或者linux系统下的路径
120      * @param filename 文件的路径 如: 二次合成2011IPTV上海文广电影123456_变形金刚.ts
121      */
122     public static String joinPath(String driverOrLpath,String filename ){
123         String d = driverOrLpath.replaceAll("[\\/]*$", "") ;
124         filename = filename.replaceAll("^[\\/]*", ""); // 把开头的 斜杠都去掉,后面统一
125         
126         return d + File.separator + filename;
127     }
128     
129     /**
130      * 功能:替换掉文件名字中的特殊字符
131      * 时间:2016-01-21
132      * @param filename
133      * @return
134      */
135     public static String removeSPEcialcharacter(String filename){
136          Pattern pattern=Pattern.compile("[u4e00-u9fa5]");//中文汉字编码区间  
137            Matcher matcher;
138            char[] array = filename.toCharArray();
139            for (int i = 0; i < array.length; i++) {
140                 if((char)(byte)array[i]!=array[i]){//取出双字节字符
141                     matcher=pattern.matcher(String.valueOf(array[i]));
142                     if(!matcher.matches()){//中文汉字无需替换
143                         filename=filename.replaceAll(String.valueOf(array[i]), "");//特殊字符用空字符串替换
144                     }
145                 }
146             }
147            return filename;
148     }
149     
150     public static void main(String[] args) {
151         
152     }
153 }
 1     /*
 2      * 如果想要获得当前文件中的文件名只需要String [] fileName = file.list();就可以了。
 3      * 如果要包括文件中的文件名就可以用递归的方式。下面是两个具体的实现。 
 4      * 其中public static String [] getFileName(String path)是只得到当前文件中的文件名。
 5      * public static void getAllFileName(String path,ArrayList<String> fileName)是包括当前文件及其子文件的文件名。
 6      */
 7     public static String[] getFileName(String path) {
 8         File file = new File(path);
 9         String[] fileName = file.list();
10         return fileName;
11     }
12     
13     public static ArrayList<String> getFilePath(String parentPath) {
14         ArrayList<String> chilDFilesPathList = new ArrayList<String>();
15         File parentFile = new File(parentPath);
16         File[] childFiles = parentFile.listFiles();
17         for (File childFile : childFiles) {
18             childFilesPathList.add(childFile.getAbsolutePath());
19         }
20         return childFilesPathList;
21     }
22 
23     public static void getAllFileName(String path, ArrayList<String> fileName) {
24         File file = new File(path);
25         File[] files = file.listFiles();
26         String[] names = file.list();
27         if (names != null)
28             fileName.addAll(Arrays.asList(names));
29         for (File a : files) {
30             if (a.isDirectory()) {
31                 getAllFileName(a.getAbsolutePath(), fileName);
32             }
33         }
34     }

 

Java中windows路径转换成linux路径等工具类

 我总结的类似相关博客:http://www.cnblogs.com/DreamDrive/p/4289860.htML

  1 import java.net.inetAddress;
  2 import java.net.UnknownHostException;
  3 import java.util.List;
  4 
  5 /**
  6  * OS Utility Class This is used to oBTain the os related VAR PRogrammatically
  7  * 
  8  * <p>
  9  * <a h ref="OSUtil.java.html"><i>View Source</i></a>
 10  * </p>
 11  * 
 12  *  13  */
 14 public class OSUtil {
 15     
 16     public static String LIUNX = "Linux";
 17     public static String WINDOWS = "Windows";
 18     
 19     
 20     /**
 21      * 功能: 将windows路径转换成linux路径
 22      */
 23     public static String convert2linuxpath(String _path){
 24         if(isLinuxSystem()){
 25             int index = _path.indexOf(":");
 26             if(index>1 || index == -1) //不含有盘符
 27 
 28                 return _path;
 29             
 30             SysStoredevMgr _sM = new SysstoredevMgr() ;
 31             List<Sysstoredev> _list = _sM.findAll() ;
 32             for( Sysstoredev _sd : _list ){
 33                 String _driver = ConvertString.ConvertStr(_sd.getDriver()) ;
 34                 if(_path.startsWith(_driver)){
 35                      return FileNameUtil.correctFileName4Linux(_path.replace(_driver, ConvertString.ConvertStr(_sd.getLpath()))) ;
 36                 }
 37             }
 38         }
 39         return _path;
 40     }
 41     
 42     
 43     /**
 44      * 获得主机名称
 45      * obtain the host name in form of string
 46      * 
 47      * @return String
 48      * @throws UnknownHostException
 49      */
 50     public static String getHostName() throws UnknownHostException {
 51         InetAddress inetaddr = InetAddress.getLocalHost();
 52         return inetaddr.getHostName();
 53     }
 54 
 55     /**
 56      * 获得主机IP
 57      * obtain the ip address of the host in form of string
 58      * 
 59      * @return String
 60      * @throws UnknownHostException
 61      */
 62     public static String getHostIP() throws UnknownHostException {
 63         InetAddress inetaddr = InetAddress.getLocalHost();
 64         return inetaddr.getHostAddress();
 65     }
 66 
 67     /**
 68      * 测试给定的主机是否是本地主机.
 69      * check if the given host is the local host
 70      * 
 71      * @param hostname String
 72      * @param hostip   String
 73      * @return boolean
 74      * @throws UnknownHostException
 75      */
 76     public static boolean isNative(String hostname, String hostip) {
 77         try {
 78             hostname = (hostname == null ? "" : hostname);
 79             hostip = (hostip == null ? "" : hostip);
 80 
 81             InetAddress inetaddr = InetAddress.getLocalHost();
 82             if (hostname.equals(""))
 83                 return inetaddr.getHostAddress().equalsIgnoreCase(hostip);
 84 
 85             if (!inetaddr.getHostName().equalsIgnoreCase(hostname))
 86                 return false;
 87 
 88             if (hostip.length() > 0) {
 89                 InetAddress[] inetaddrs = InetAddress.getAllByName(inetaddr.getHostName());
 90                 boolean b = false;
 91                 for (int i = 0; i < inetaddrs.length; i++) {
 92                     if (inetaddrs[i].getHostAddress().equalsIgnoreCase(hostip)) {
 93                         b = true;
 94                         break;
 95                     }
 96                 }
 97                 return b;
 98             } else {
 99                 return true;
100             }
101         } catch (UnknownHostException e) {
102             return false;
103         }
104     }
105 
106     /**
107      * 获得指定的环境变量的值
108      * @param envvarname
109      * @param defaultvalue
110      * @return
111      */
112     public static String getEnvironmentVar(String envvarname,
113             String defaultvalue) {
114         String str = System.getenv(envvarname);
115         str = (str == null ? "" : str);
116         return (str.length() == 0 ? defaultvalue : str);
117     }
118     
119     
120     /**
121      * 判断是否是Linux操作系统
122      * @return
123      */
124     public static Boolean isLinuxSystem(){
125         if(OSUtil.LIUNX.equals(System.getProperty("os.name"))){
126             return true;
127         }
128         return false;
129     }
130     
131 
132     public static void main(String[] args) throws Exception{
133         
134         System.out.println(OSUtil.convert2linuxPath("M:\hello\abc.txt"));
135         
136         System.out.println(OSUtil.convert2linuxPath("M:\hello/abc.txt"));
137         
138         System.out.println(OSUtil.convert2linuxPath("/linux/p\u.png"));
139         
140     }
141 
142 }

 

脚本宝典总结

以上是脚本宝典为你收集整理的Java 文件名操作的相关工具类 & Java中windows路径转换成linux路径等工具类全部内容,希望文章能够帮你解决Java 文件名操作的相关工具类 & Java中windows路径转换成linux路径等工具类所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。