Java Tutorial/File/Path

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Absolute and Relative Paths

   <source lang="java">

import java.io.File; public class MainClass {

 public static void main(String[] a) {
   File myFile = new File("output.txt");
   System.out.println(myFile.getAbsolutePath());
 }

}</source>



C:\Java_Dev\eclipse31\Apache Common\output.txt


Absolute path and relative path

   <source lang="java">

import java.io.File; public class MainClass {

 public static void main(String[] args) {
   File absolute = new File("/public/html/javafaq/index.html");
   File relative = new File("html/javafaq/index.html");
   System.out.println("absolute: ");
   System.out.println(absolute.getName());
   System.out.println(absolute.getPath());
   System.out.println("relative: ");
   System.out.println(relative.getName());
   System.out.println(relative.getPath());
 }

}</source>



absolute: 
index.html
\public\html\javafaq\index.html
relative: 
index.html
html\javafaq\index.html


Build a path- but do not create it

   <source lang="java">

import java.io.File; import java.io.IOException; public class Utils {

 /**
  * Build a path- but do not create it
  * 
  * @param parent
  * @param subDirectory
  * @return a File representing the path
  */
 public static File getDirectoryPath(File parent, String subDirectory) {
     File result = null;
     if (parent != null) {
         result = new File(parent, subDirectory);
     }
     return result;
 }

}</source>





Build a relative path to the given base path

   <source lang="java">

/*

 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

import java.io.File; import java.io.IOException; public class Main{

 /**
  * Build a relative path to the given base path.
  * @param base - the path used as the base
  * @param path - the path to compute relative to the base path
  * @return A relative path from base to path
  * @throws IOException
  */ 
 public static String findRelativePath(String base, String path)
    throws IOException
 {
    String a = new File(base).getCanonicalFile().toURI().getPath();
    String b = new File(path).getCanonicalFile().toURI().getPath();
    String[] basePaths = a.split("/");
    String[] otherPaths = b.split("/");
    int n = 0;
    for(; n < basePaths.length && n < otherPaths.length; n ++)
    {
       if( basePaths[n].equals(otherPaths[n]) == false )
          break;
    }
    System.out.println("Common length: "+n);
    StringBuffer tmp = new StringBuffer("../");
    for(int m = n; m < basePaths.length - 1; m ++)
       tmp.append("../");
    for(int m = n; m < otherPaths.length; m ++)
    {
       tmp.append(otherPaths[m]);
       tmp.append("/");
    }
    return tmp.toString();
 }

}</source>





Compare two file paths

   <source lang="java">

import java.io.File; public class Main {

 public static void main(String[] args) {
   File file1 = new File("C:/File/demo1.txt");
   File file2 = new File("C:/FileIO/demo1.txt");
   if (file1.rupareTo(file2) == 0) {
     System.out.println("Both paths are same!");
   } else {
     System.out.println("Paths are not same!");
   }
 }

}</source>





Construct file path

   <source lang="java">

import java.io.File; public class Main {

 public static void main(String[] args) {
   String filePath = File.separator + "Java" + File.separator + "IO";
   File file = new File(filePath);
   System.out.println(file.getPath());
 }

} // \Java\IO</source>





Convert a file path into a File object with an absolute path relative to a passed in root.

   <source lang="java">

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /*

Derby - Class org.apache.derby.iapi.util.PropertyUtil
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

public class Main {

 /**
 Convert a file path into a File object with an absolute path
 relative to a passed in root. If path is absolute then
 a file object constructed from new File(path) is returned,
 otherwise a file object is returned from new File(root, path)
 if root is not null, otherwise null is returned.
  • /

public static File getAbsoluteFile(File root, String path) {

 File file = new File(path);
 if (file.isAbsolute())
   return file;
 if (root == null)
   return null;
 return new File(root, path);

} }</source>





Convert a list of path elements to a platform-specific path.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/

import java.io.File; /**

* 
* FileUtils is a collection of routines for common file system operations.
* 
* @author Dan Jemiolo (danj)
* 
*/

public final class FileUtils {

 /**
  * Convert a list of path elements to a platform-specific path.
  * 
  * @param strings
  *          Elements in a path
  * @return an absolute path using the current platform"s
  *         File.separator
  */
 public static String makePath(String[] strings) {
   String result = "";
   for (int i = 0; i < strings.length; i++)
     result += File.separator + strings[i];
   return result;
 }

}</source>





Determining If Two Filename Paths Refer to the Same File

   <source lang="java">

import java.io.File; public class Main {

 public static void main(String[] argv) throws Exception {
   File file1 = new File("./filename");
   File file2 = new File("filename");
   System.out.println(file1.equals(file2));
   file1 = file1.getCanonicalFile();
   file2 = file2.getCanonicalFile();
   System.out.println(file1.equals(file2));
 }

}</source>





Display directory tree

   <source lang="java">

import java.io.File; class DirectoryTree {

 public static void main(String args[]) {
   File file = new File(args[0]);
   if (!file.exists()) {
     System.out.println(args[0] + " does not exist.");
     return;
   }
   tree(args[0]);
 }
 public static void tree(String filename) {
   File file = new File(filename);
   if (!file.isDirectory()) {
     System.out.println(filename);
     return;
   }
   String files[] = file.list();
   for (int i = 0; i < files.length; i++) {
     tree(filename + File.separator + files[i]);
   }
 }

}</source>





File Objects: specifies a path for a file or a directory

   <source lang="java">

import java.io.File; public class MainClass {

 public static void main(String[] a) {
   File myDir = new File("C:/jdk1.5.0/src/java/io");
   System.out.println(myDir);
 }

}</source>



C:\jdk1.5.0\src\java\io


Filtered Directory Tree

   <source lang="java">

import java.io.File; class FilteredDirectoryTree {

 public static void main(String args[]) {
   tree(args[0], "txt");
 }
 public static void tree(String filename, String suffix) {
   File file = new File(filename);
   if (!file.isDirectory()) {
     if (suffix == null || filename.endsWith(suffix))
       System.out.println(filename);
     return;
   }
   String files[] = file.list();
   for (int i = 0; i < files.length; i++) {
     tree(filename + File.separator + files[i], suffix);
   }
 }

}</source>





Get file separator using System class

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   System.out.println(System.getProperty("file.separator"));
 }

}</source>





Get relative path

   <source lang="java">

import java.io.File;

public class Main {

 public static String relative( final File base, final File file ) {
   final int rootLength = base.getAbsolutePath().length();
   final String absFileName = file.getAbsolutePath();
   final String relFileName = absFileName.substring(rootLength + 1);
   return relFileName;

} }</source>





Getting an Absolute Filename Path from a Relative Filename parent Path

   <source lang="java">

import java.io.File; public class Main {

 public static void main(String[] argv) throws Exception {
   File file = new File(".." + File.separatorChar + "filename.txt");
   file = file.getAbsoluteFile();
 }

}</source>





Getting an Absolute Filename Path from a Relative Filename Path

   <source lang="java">

import java.io.File; public class Main {

 public static void main(String[] argv) throws Exception {
   File file = new File("filename.txt");
   file = file.getAbsoluteFile();
 }

}</source>





Getting an Absolute Filename Path from a Relative Filename with Path

   <source lang="java">

import java.io.File; public class Main {

 public static void main(String[] argv) throws Exception {
   File file = new File("dir" + File.separatorChar + "filename.txt");
   file = file.getAbsoluteFile();
 }

}</source>





Match a path which may contain a wildcard

   <source lang="java">

/* Copyright (c) 2003 eInnovation Inc. All rights reserved This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

  • /

/*--

Copyright (C) 2001-2002 Anthony Eden.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions, and the disclaimer that follows
   these conditions in the documentation and/or other materials
   provided with the distribution.
3. The name "JPublish" must not be used to endorse or promote products
   derived from this software without prior written permission.  For
   written permission, please contact me@anthonyeden.ru.
4. Products derived from this software may not be called "JPublish", nor
   may "JPublish" appear in their name, without prior written permission
   from Anthony Eden (me@anthonyeden.ru).
In addition, I request (but do not require) that you include in the
end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
    "This product includes software developed by
     Anthony Eden (http://www.anthonyeden.ru/)."
THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
For more information on JPublish, please see <http://www.jpublish.org/>.
*/

/**

* Utility class for working with request paths.
*
* @author Anthony Eden
*/

public final class PathUtilities {

 private static final String WILDCARD = "*";
 /**
  * Match a path which may contain a wildcard.
  *
  * @param requestPath The request path submitted by the client
  * @param exPath The match path with * wildcard
  *
  * @return DOCME
  */
 public static boolean match(String requestPath, String wildcardPath)
 {
   //  *somestuffhereverylong*  != stuff
   if( wildcardPath.length() - 2 > requestPath.length())
   {
     return false;
   }
   
   //log.debug("match(" + requestPath + "," + exPath + ")");
   int wildcardIndex = wildcardPath.indexOf(WILDCARD);
   if (wildcardIndex == -1)
   {
     return requestPath.equalsIgnoreCase(wildcardPath);
   }
   else if( wildcardPath.charAt(0) == "*" && wildcardPath.charAt(wildcardPath.length()-1) == "*" )
   {
     String path = wildcardPath.substring(1,wildcardPath.length()-1);
     return requestPath.indexOf(path) > -1;
   }
   else if (wildcardIndex == (wildcardPath.length() - 1)) //ends with *
   {
       //log.debug("Wildcard appears at end of match path.");
       String checkString = wildcardPath.substring(0, wildcardPath.length() - 1);
       //  /stuff/* -> /stuff     /stuff/abc* != /stuff/ab
       
       if( checkString.charAt(checkString.length()-1) == "/")
       {
         checkString = checkString.substring(0,checkString.length() - 1);
       }
       //log.debug("String after wildcard removed: " + checkString);
       boolean answer = requestPath.startsWith(checkString);
       //log.debug("Does " + requestPath + " start with " + checkString + "? " + answer);
       return answer;
   }
   else if( wildcardPath.charAt(0) == "*")
   {
     String checkString = wildcardPath.substring(1);
     //log.debug("String after wildcard removed: " + checkString);
     boolean answer = requestPath.endsWith(checkString);
     return answer;
   }
   else
   {
     //log.debug("Wildcard appears in the middle of the string");
     String preMatch = wildcardPath.substring(0, wildcardIndex);
     String postMatch = wildcardPath.substring(wildcardIndex + 1);
     return requestPath.startsWith(preMatch) && requestPath.endsWith(postMatch);
   }
 }

}</source>





Merges the two paths to create a valid version of the second path

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/

import java.io.File; /**

* 
* FileUtils is a collection of routines for common file system operations.
* 
* @author Dan Jemiolo (danj)
* 
*/

public final class FileUtils {

 /**
  * 
  * Merges the two paths to create a valid version of the second path. This
  * method should be used when you encounter a relative path in a document and
  * must resolve it based on the path of the current document. An example would
  * be: 
*
* original path - files/customers/Orders.xml
*
* relative path - ../Accounts.xml
*
* result - files/customers/Accounts.xml
*
* The only time this method cannot be used is if the original path is for a * file that is in the root (has no directory as part of its path) and the * relative path starts with "..". * * @param originalPath * The path of the file that references another file. * * @param relativePath * The path of the other file, which is relative to the original. * * @return A proper path for the other file, one that can be used to open and * verify the file. * */ public static String createRelativePath(String originalPath, String relativePath) { if (originalPath == null) throw new NullPointerException("NullOriginalPath"); if (relativePath == null) throw new NullPointerException("NullRelativePath"); // // remove ./ if present // if (relativePath.startsWith("./")) relativePath = relativePath.substring(2); // // remove any .. reference by taking off the last section/ of // the original path // if (relativePath.startsWith("../")) { int slash = originalPath.lastIndexOf("/"); originalPath = originalPath.substring(0, slash); relativePath = relativePath.substring(3); } int slash = originalPath.lastIndexOf("/"); if (slash < 0) return relativePath; String dir = originalPath.substring(0, slash + 1); return dir + relativePath; }

}</source>





Portable Path Considerations

   <source lang="java">

import java.io.File; public class MainClass {

 public static void main(String[] a) {
   File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator + "src"
       + File.separator + "java" + File.separator + "io", "File.java");
   System.out.println(myFile);
 }

}</source>



C:\jdk1.5.0\src\java\io\File.java


Remove file information from a filename returning only its path component

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.File;

public class Main {

 /**
  * Remove file information from a filename returning only its path component
  * 
  * @param filename
  *            The filename
  * @return The path information
  */
 public static String pathComponent(String filename) {
     int i = filename.lastIndexOf(File.separator);
     return (i > -1) ? filename.substring(0, i) : filename;
 }

}</source>





Remove path and file information from a filename returning only its extension component

   <source lang="java">

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /*

Derby - Class org.apache.derby.iapi.util.PropertyUtil
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

public class Main {

 /**
  * Remove path and file information from a filename returning only its
  * extension  component
  *
  * @param uri The filename
  * @return The filename extension (with starting dot!) or null if filename extension is not found
  */
 public static String getExtension(String uri) {
     int dot = uri.lastIndexOf(".");
     if (dot > -1) {
         uri = uri.substring(dot);
         int slash = uri.lastIndexOf("/");
         if (slash > -1) {
             return null;
         } else {
             int sharp = uri.lastIndexOf("#");
             if (sharp > -1) {
                 // uri starts with dot already
                 return uri.substring(0, sharp);
             } else {
                 int mark = uri.lastIndexOf("?");
                 if (mark > -1) {
                     // uri starts with dot already
                     return uri.substring(0, mark);
                 } else {
                     return uri;
                 }
             }
         }
     } else {
         return null;
     }
 }

}</source>





Remove path information from a filename returning only its file component

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.File;

public class Main {

 /**
  * Remove path information from a filename returning only its file component
  * 
  * @param filename
  *            The filename
  * @return The filename sans path information
  */
 public static String fileComponent(String filename) {
     int i = filename.lastIndexOf(File.separator);
     return (i > -1) ? filename.substring(i + 1) : filename;
 }

}</source>





Return a file with the given filename creating the necessary directories if not present.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.File;

public class Main {

 /**
  * Return a file with the given filename creating the necessary directories
  * if not present.
  * 
  * @param filename
  *            The file
  * @return The created File instance
  */
 public static File createFile(File destDir, String filename) {
     File file = new File(destDir, filename);
     File parent = file.getParentFile();
     if (parent != null)
         parent.mkdirs();
     return file;
 }

}</source>





Return the page type extracting it from the path

   <source lang="java">

/* Copyright (c) 2003 eInnovation Inc. All rights reserved This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

  • /

/*--

Copyright (C) 2001-2002 Anthony Eden.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions, and the disclaimer that follows
   these conditions in the documentation and/or other materials
   provided with the distribution.
3. The name "JPublish" must not be used to endorse or promote products
   derived from this software without prior written permission.  For
   written permission, please contact me@anthonyeden.ru.
4. Products derived from this software may not be called "JPublish", nor
   may "JPublish" appear in their name, without prior written permission
   from Anthony Eden (me@anthonyeden.ru).
In addition, I request (but do not require) that you include in the
end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
    "This product includes software developed by
     Anthony Eden (http://www.anthonyeden.ru/)."
THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
For more information on JPublish, please see <http://www.jpublish.org/>.
*/

/**

* Utility class for working with request paths.
*
* @author Anthony Eden
*/

public final class PathUtilities {

 private static final String WILDCARD = "*";
 /**
  * Return the page type extracting it from the path.  For example: index.html would return
  * "html" as the page type.  If the type cannot be determined then this method returns null.
  *
  * @param path The path
  *
  * @return The page type
  */
 public static String extractPageType(String path)
 {
   if (path == null)
   {
     return null;
   }
   
   int dotIndex = path.lastIndexOf(".");
   if (dotIndex == -1)
   {
     return null;
   }
   String pageType = path.substring(dotIndex + 1);
   return pageType;
 }

}</source>





Strip a filename of its last extension (the portion immediately following the last dot character, if any)

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.File;

public class Main {

 /**
  * Strip a filename of its last extension (the portion immediately
  * following the last dot character, if any)
  * 
  * @param filename
  *            The filename
  * @return The filename sans extension
  */
 public static String baseName(String filename) {
     int i = filename.lastIndexOf(".");
     return (i > -1) ? filename.substring(0, i) : filename;
 }

}</source>





Universal Naming Convention

   <source lang="java">

import java.io.File; public class MainClass {

 public static void main(String[] a) {
   File myFile = new File("//myPC/shared/jdk1.5.0/src/java/io", "File.java");
   System.out.println(myFile);
   myFile = new File(File.separator + File.separator + "myPC" + File.separator + "shared"
       + File.separator + "jdk1.4" + File.separator + "src" + File.separator + "java"
       + File.separator + "io", "File.java");
   System.out.println(myFile);
 }

}</source>



\\myPC\shared\jdk1.5.0\src\java\io\File.java
\\myPC\shared\jdk1.4\src\java\io\File.java


Using double slash to escape

   <source lang="java">

import java.io.File; public class MainClass {

 public static void main(String[] a) {
   File myDir = new File("C:\\jdk1.5.0\\src\\java\\io");
   System.out.println(myDir);
 }

}</source>



C:\jdk1.5.0\src\java\io


Using the second constructor: C:/jdksrc/java/io

   <source lang="java">

import java.io.File; public class MainClass {

 public static void main(String[] a) {
   File myFile = new File("C:/jdk1.5.0/src/java/io", "File.java");
   System.out.println(myFile);
 }

}</source>



C:\jdk1.5.0\src\java\io\File.java