Java Windows File Read File Not Found

The Path class includes various methods that can be used to obtain information nigh the path, access elements of the path, convert the path to other forms, or extract portions of a path. There are also methods for matching the path string and methods for removing redundancies in a path. This lesson addresses these Path methods, sometimes called syntactic operations, because they operate on the path itself and don't access the file system.

This department covers the following:

  • Creating a Path
  • Retrieving Data Nigh a Path
  • Removing Redundancies from a Path
  • Converting a Path
  • Joining 2 Paths
  • Creating a Path Betwixt Two Paths
  • Comparison Two Paths

Creating a Path

A Path instance contains the data used to specify the location of a file or directory. At the fourth dimension it is divers, a Path is provided with a series of one or more names. A root element or a file name might be included, but neither are required. A Path might consist of just a single directory or file proper noun.

Y'all tin easily create a Path object by using one of the following become methods from the Paths (note the plural) helper grade:

Path p1 = Paths.get("/tmp/foo"); Path p2 = Paths.get(args[0]); Path p3 = Paths.become(URI.create("file:///Users/joe/FileTest.java"));          

The Paths.get method is shorthand for the post-obit code:

Path p4 = FileSystems.getDefault().getPath("/users/sally");          

The following case creates /u/joe/logs/foo.log assuming your dwelling directory is /u/joe, or C:\joe\logs\foo.log if you are on Windows.

Path p5 = Paths.get(System.getProperty("user.domicile"),"logs", "foo.log");          

Retrieving Information well-nigh a Path

Yous can recollect of the Path equally storing these name elements as a sequence. The highest element in the directory structure would exist located at index 0. The lowest element in the directory construction would be located at index [due north-1], where due north is the number of proper name elements in the Path. Methods are available for retrieving individual elements or a subsequence of the Path using these indexes.

The examples in this lesson use the post-obit directory structure.

Sample directory structure
Sample Directory Structure

The following code snippet defines a Path instance and then invokes several methods to obtain information about the path:

// None of these methods requires that the file respective // to the Path exists. // Microsoft Windows syntax Path path = Paths.get("C:\\home\\joe\\foo");  // Solaris syntax Path path = Paths.get("/habitation/joe/foo");  System.out.format("toString: %s%n", path.toString()); System.out.format("getFileName: %s%north", path.getFileName()); Organisation.out.format("getName(0): %southward%north", path.getName(0)); System.out.format("getNameCount: %d%n", path.getNameCount()); System.out.format("subpath(0,2): %due south%n", path.subpath(0,2)); System.out.format("getParent: %south%n", path.getParent()); System.out.format("getRoot: %south%n", path.getRoot());          

Hither is the output for both Windows and the Solaris Os:

Method Invoked Returns in the Solaris OS Returns in Microsoft Windows Comment
toString /abode/joe/foo C:\home\joe\foo Returns the cord representation of the Path. If the path was created using Filesystems.getDefault().getPath(String) or Paths.get (the latter is a convenience method for getPath), the method performs minor syntactic cleanup. For example, in a UNIX operating organization, it will correct the input cord //home/joe/foo to /dwelling/joe/foo.
getFileName foo foo Returns the file name or the last element of the sequence of name elements.
getName(0) home home Returns the path element corresponding to the specified alphabetize. The 0th element is the path element closest to the root.
getNameCount iii 3 Returns the number of elements in the path.
subpath(0,2) dwelling/joe habitation\joe Returns the subsequence of the Path (not including a root element) every bit specified past the beginning and ending indexes.
getParent /home/joe \domicile\joe Returns the path of the parent directory.
getRoot / C:\ Returns the root of the path.

The previous example shows the output for an absolute path. In the following example, a relative path is specified:

// Solaris syntax Path path = Paths.become("sally/bar"); or // Microsoft Windows syntax Path path = Paths.get("emerge\\bar");          

Here is the output for Windows and the Solaris Os:

Method Invoked Returns in the Solaris Os Returns in Microsoft Windows
toString sally/bar emerge\bar
getFileName bar bar
getName(0) emerge sally
getNameCount ii 2
subpath(0,1) sally sally
getParent sally sally
getRoot null naught

Removing Redundancies From a Path

Many file systems use "." notation to announce the electric current directory and ".." to denote the parent directory. You might have a state of affairs where a Path contains redundant directory information. Perhaps a server is configured to relieve its log files in the "/dir/logs/." directory, and yous want to delete the trailing "/." notation from the path.

The following examples both include redundancies:

/home/./joe/foo /home/sally/../joe/foo          

The normalize method removes any redundant elements, which includes any "." or " directory/.." occurrences. Both of the preceding examples normalize to /home/joe/foo.

It is important to note that normalize doesn't check at the file organization when it cleans up a path. Information technology is a purely syntactic functioning. In the second example, if sally were a symbolic link, removing sally/.. might outcome in a Path that no longer locates the intended file.

To clean up a path while ensuring that the result locates the correct file, you lot can utilise the toRealPath method. This method is described in the next section, Converting a Path.

Converting a Path

You can use three methods to convert the Path. If you demand to convert the path to a string that can exist opened from a browser, you can use toUri. For example:

Path p1 = Paths.get("/abode/logfile"); // Result is            file:///home/logfile            Organisation.out.format("%south%north", p1.toUri());          

The toAbsolutePath method converts a path to an accented path. If the passed-in path is already absolute, it returns the same Path object. The toAbsolutePath method can exist very helpful when processing user-entered file names. For example:

public class FileTest {     public static void main(String[] args) {          if (args.length < 1) {             Arrangement.out.println("usage: FileTest file");             System.go out(-1);         }          // Converts the input string to a Path object.         Path inputPath = Paths.get(args[0]);            // Converts the input Path         // to an absolute path.         // More often than not, this means prepending         // the current working         // directory.  If this example         // were called like this:         //     java FileTest foo         // the getRoot and getParent methods         // would return null         // on the original "inputPath"         // instance.  Invoking getRoot and         // getParent on the "fullPath"         // instance returns expected values.         Path fullPath = inputPath.toAbsolutePath();            } }          

The toAbsolutePath method converts the user input and returns a Path that returns useful values when queried. The file does not demand to exist for this method to work.

The toRealPath method returns the real path of an existing file. This method performs several operations in one:

  • If true is passed to this method and the file system supports symbolic links, this method resolves any symbolic links in the path.
  • If the Path is relative, it returns an accented path.
  • If the Path contains any redundant elements, it returns a path with those elements removed.

This method throws an exception if the file does non exist or cannot be accessed. Y'all can grab the exception when y'all want to handle whatever of these cases. For example:

try {     Path fp = path.toRealPath(); } catch (NoSuchFileException x) {     System.err.format("%south: no such" + " file or directory%n", path);     // Logic for example when file doesn't exist. } catch (IOException x) {     Arrangement.err.format("%s%northward", ten);     // Logic for other sort of file fault. }          

Joining Two Paths

Yous can combine paths by using the resolve method. You laissez passer in a partial path , which is a path that does not include a root element, and that partial path is appended to the original path.

For example, consider the following lawmaking snippet:

// Solaris Path p1 = Paths.get("/domicile/joe/foo"); // Result is            /domicile/joe/foo/bar            System.out.format("%southward%north", p1.resolve("bar"));  or  // Microsoft Windows Path p1 = Paths.go("C:\\home\\joe\\foo"); // Issue is            C:\home\joe\foo\bar            System.out.format("%south%n", p1.resolve("bar"));          

Passing an accented path to the resolve method returns the passed-in path:

// Result is            /habitation/joe            Paths.become("foo").resolve("/abode/joe");          

Creating a Path Between Two Paths

A common requirement when you are writing file I/O lawmaking is the capability to construct a path from one location in the file organization to some other location. You tin can meet this using the relativize method. This method constructs a path originating from the original path and ending at the location specified by the passed-in path. The new path is relative to the original path.

For example, consider ii relative paths defined every bit joe and sally:

Path p1 = Paths.get("joe"); Path p2 = Paths.get("sally");          

In the absence of any other information, it is assumed that joe and emerge are siblings, meaning nodes that reside at the same level in the tree structure. To navigate from joe to sally, yous would look to first navigate one level upward to the parent node then down to emerge:

// Result is            ../sally            Path p1_to_p2 = p1.relativize(p2); // Event is            ../joe            Path p2_to_p1 = p2.relativize(p1);          

Consider a slightly more complicated example:

Path p1 = Paths.go("home"); Path p3 = Paths.get("home/sally/bar"); // Event is            emerge/bar            Path p1_to_p3 = p1.relativize(p3); // Result is            ../..            Path p3_to_p1 = p3.relativize(p1);          

In this example, the two paths share the same node, dwelling. To navigate from dwelling to bar, you lot showtime navigate one level down to sally and so 1 more level down to bar. Navigating from bar to home requires moving upwards ii levels.

A relative path cannot be synthetic if only one of the paths includes a root chemical element. If both paths include a root chemical element, the capability to construct a relative path is system dependent.

The recursive Copy example uses the relativize and resolve methods.

Comparison Two Paths

The Path class supports equals, enabling you to examination two paths for equality. The startsWith and endsWith methods enable yous to test whether a path begins or ends with a detail string. These methods are easy to use. For example:

Path path = ...; Path otherPath = ...; Path beginning = Paths.get("/abode"); Path ending = Paths.get("foo");  if (path.equals(otherPath)) {     //            equality logic here            } else if (path.startsWith(starting time)) {     //            path begins with "/home"            } else if (path.endsWith(catastrophe)) {     //            path ends with "foo"            }          

The Path course implements the Iterable interface. The iterator method returns an object that enables you to iterate over the name elements in the path. The outset element returned is that closest to the root in the directory tree. The following code snippet iterates over a path, printing each name element:

Path path = ...; for (Path proper noun: path) {     System.out.println(proper noun); }          

The Path class also implements the Comparable interface. You lot can compare Path objects by using compareTo which is useful for sorting.

Y'all can also put Path objects into a Collection. See the Collections trail for more information about this powerful feature.

When y'all want to verify that two Path objects locate the same file, you tin can use the isSameFile method, as described in Checking Whether 2 Paths Locate the Same File.

castillosirstion66.blogspot.com

Source: https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

0 Response to "Java Windows File Read File Not Found"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel