Java Tutorial/File/Path — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 05:20, 1 июня 2010
Содержание
- 1 Absolute and Relative Paths
- 2 Absolute path and relative path
- 3 Build a path- but do not create it
- 4 Build a relative path to the given base path
- 5 Compare two file paths
- 6 Construct file path
- 7 Convert a file path into a File object with an absolute path relative to a passed in root.
- 8 Convert a list of path elements to a platform-specific path.
- 9 Determining If Two Filename Paths Refer to the Same File
- 10 Display directory tree
- 11 File Objects: specifies a path for a file or a directory
- 12 Filtered Directory Tree
- 13 Get file separator using System class
- 14 Get relative path
- 15 Getting an Absolute Filename Path from a Relative Filename parent Path
- 16 Getting an Absolute Filename Path from a Relative Filename Path
- 17 Getting an Absolute Filename Path from a Relative Filename with Path
- 18 Match a path which may contain a wildcard
- 19 Merges the two paths to create a valid version of the second path
- 20 Portable Path Considerations
- 21 Remove file information from a filename returning only its path component
- 22 Remove path and file information from a filename returning only its extension component
- 23 Remove path information from a filename returning only its file component
- 24 Return a file with the given filename creating the necessary directories if not present.
- 25 Return the page type extracting it from the path
- 26 Strip a filename of its last extension (the portion immediately following the last dot character, if any)
- 27 Universal Naming Convention
- 28 Using double slash to escape
- 29 Using the second constructor: C:/jdksrc/java/io
Absolute and Relative Paths
import java.io.File;
public class MainClass {
public static void main(String[] a) {
File myFile = new File("output.txt");
System.out.println(myFile.getAbsolutePath());
}
}
C:\Java_Dev\eclipse31\Apache Common\output.txt
Absolute path and relative path
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());
}
}
absolute: index.html \public\html\javafaq\index.html relative: index.html html\javafaq\index.html
Build a path- but do not create it
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;
}
}
Build a relative path to the given base path
/*
* 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();
}
}
Compare two file paths
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!");
}
}
}
Construct file path
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
Convert a file path into a File object with an absolute path relative to a passed in root.
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);
}
}
Convert a list of path elements to a platform-specific path.
/*
* 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
* <code>File.separator</code>
*/
public static String makePath(String[] strings) {
String result = "";
for (int i = 0; i < strings.length; i++)
result += File.separator + strings[i];
return result;
}
}
Determining If Two Filename Paths Refer to the Same File
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));
}
}
Display directory tree
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]);
}
}
}
File Objects: specifies a path for a file or a directory
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);
}
}
C:\jdk1.5.0\src\java\io
Filtered Directory Tree
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);
}
}
}
Get file separator using System class
public class Main {
public static void main(String[] args) {
System.out.println(System.getProperty("file.separator"));
}
}
Get relative path
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;
}
}
Getting an Absolute Filename Path from a Relative Filename parent Path
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();
}
}
Getting an Absolute Filename Path from a Relative Filename Path
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("filename.txt");
file = file.getAbsoluteFile();
}
}
Getting an Absolute Filename Path from a Relative Filename with Path
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();
}
}
Match a path which may contain a wildcard
/*
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);
}
}
}
Merges the two paths to create a valid version of the second path
/*
* 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: <br>
* <br>
* <b>original path</b> - files/customers/Orders.xml <br>
* <br>
* <b>relative path</b> - ../Accounts.xml <br>
* <br>
* <b>result</b> - files/customers/Accounts.xml <br>
* <br>
* 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;
}
}
Portable Path Considerations
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);
}
}
C:\jdk1.5.0\src\java\io\File.java
Remove file information from a filename returning only its path component
/*
* 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;
}
}
Remove path and file information from a filename returning only its extension component
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;
}
}
}
Remove path information from a filename returning only its file component
/*
* 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;
}
}
Return a file with the given filename creating the necessary directories if not present.
/*
* 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;
}
}
Return the page type extracting it from the path
/*
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;
}
}
Strip a filename of its last extension (the portion immediately following the last dot character, if any)
/*
* 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 <i>last</i> 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;
}
}
Universal Naming Convention
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);
}
}
\\myPC\shared\jdk1.5.0\src\java\io\File.java \\myPC\shared\jdk1.4\src\java\io\File.java
Using double slash to escape
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);
}
}
C:\jdk1.5.0\src\java\io
Using the second constructor: C:/jdksrc/java/io
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);
}
}
C:\jdk1.5.0\src\java\io\File.java