Java File Input and Output


Java File Input and Output:

  • A file is identified by its path through the file system, beginning from the root node.

  • A symbolic link is a special file that serves as a reference to another file. when a symbolic link is deleted, or renamed then link itself is deleted, or renamed and not the target of the link.

  • A Path object contains the file name and directory list used to construct the path, and is used to examine, locate, and manipulate files.

  • Methods in the Files class are useful to check the existence of the file corresponding to the Path, create the file, open it, delete it, change its permissions, and so on.

Path Operations:
  • A Path can be created by calling static get() method on Paths (plural) helper class.

  Path p1 = Paths.get(“/home/work/sample”) ;                                                                                 Path p2 = Paths.get(URI.create(“file:///home/temp/var”));                              

Paths.get() method is a short hand for below method call on FileSystems helper class.

Path p3 = FileSystems.getDefault().getPath(“/opt/test/sample”);

  • Below are a few important useful methods on Path object.

 p1.toString()                ? /home/work/sample                                                                        p1.getFileName()       ? sample (Returns file name or last element of path)                p2.getName(0)           ? home (Returns 0th element in path)                              p2.getNameCount()   ? 3 (Total no of name elements in path)                            p3.getSubpath(0,2)   ? /opt/test                                                                                    p3.getParent()            ? /opt/test (Returns parent directory path)                                p3.getRoot()               ? /

  • The normalize method removes any redundant elements, which includes any “.” or “directory/..” occurrences.

 Path p4 = Paths.get(“/home/sample/../var/one”) ;                                                          p4.normalize()           ? /home/sample/var/one

  • Convert path to URI, that can be opened from a browser.                                                   p1.toUri()                      ? file:///home/work/sample  

The toAbsolutePath() method converts a path to an absolute path.

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 absolute path.
    • If the Path contains any redundant elements, it returns a path with those elements removed.
  •  Combine paths by using the resolve() method.

p1.resolve(“bar/one”) ? /home/work/sample/bar/one   

  • The Path class supports equals, to test two paths for equality. The startsWith and endsWith methods are also available to test whether a path begins or ends with a particular string.

 Path start = Paths.get(“/home”) ;                                                                                                          Path end = Paths.get(“var”) ;                                                                                                                        if (p1.startsWith(start)) ? returns true                                                                                                    if (p2.endsWith(end))   ? returns true

File Operations:

Files class provides rich set of static methods for reading, writing, and manipulating files and directories.

    • Files.createFile(path)             – Creates empty file
    • Files.exists(Path)                   – Checks whether a file exists at given path.
    • Files.notExists(Path)              – Checks whether a file doesn’t exist at given path.
    • Files.isReadable(Path)           – Checks whether file is readable.
    • Files.isWritable(Path)             – Checks whether file is writable.
    • Files.isExecutable(Path)        – Checks whether file is executable.
    • Files.isSameFile(Path, Path) – Compares two paths to see if they locate the same file.
    • Files.delete(Path)                    – Deletes a file or dir at given path.
    • Files.deleteIfExists(Path)       – Deletes a file, but if the file doesn’t exist, no exception is thrown.
    • Files.copy(Path1, Path2, REPLACE_EXISTING) – Copies files from path1 to path2.
    • Files.move(Path1, Path2, REPLACE_EXISTING) – Moves files from path1 to path2.
    • Files.size(Path)                           – Returns the size of the specified file in bytes.
    • Files.isDirectory(Path, LinkOption) – Checks whether given file is a directory.
    • Files.isRegularFile(Path, LinkOption…)
    • Files.isSymbolicLink(Path)     – Returns true if specified Path is a symbolic link.
    • Files.isHidden(Path)
    • Files.getLastModifiedTime(Path, LinkOption…)
    • Files.setLastModifiedTime(Path, FileTime)
    • Files.getOwner(Path, LinkOption…)
    • Files.setOwner(Path, UserPrincipal)

Creating Symbolic Links:

  Path newLlink = …;                                                                                                                                   Path target = …;                                                                                       Files.createSymbolicLink(newLink, target);

Creating a Hard Link:

Hard (or regular) link to an existing file.

Path newLink = …;                                                                                                                                         Path existingFile = …;                                                                                         Files.createLink(newLink, existingFile);

Reading all bytes or lines from a file:

byte[] fileArray = Files.readAllBytes(Path)

Writing all bytes or lines to a file:

byte[] buf = …;                                                                                                                     Files.write(file, buf);

Reading a File by Using Buffered Stream I/O:

 Charset charset = Charset.forName(“US-ASCII”);                                                              BufferedReader reader = Files.newBufferedReader(path, charset) ;                                                String line = null;                                                                                                                                            while ((line = reader.readLine()) != null)                        System.out.println(line);

Writing a File by Using Buffered Stream I/O:

 String s = …;                                                                                                                                      BufferedWriter writer = Files.newBufferedWriter(path, charset);                                          writer.write(s, 0, s.length());

Reading a File by Using Stream I/O:

InputStream in                = Files.newInputStream(path) ;                                                   BufferedReader reader = new BufferedReader(new InputStreamReader(in)) 

Creating and Writing a File by Using Stream I/O:

 String s = …;                                                                                                                                            byte [] data = s.getBytes();                                                                                                OutputStream out = new  BufferedOutputStream(Files.newOutputStream(CREATE, APPEND)) ;  out.write(data, 0, data.length);

Note:    All methods that access the file system can throw an IOException.


Profile photo of Siva

About Siva

Senior Hadoop developer with 4 years of experience in designing and architecture solutions for the Big Data domain and has been involved with several complex engagements. Technical strengths include Hadoop, YARN, Mapreduce, Hive, Sqoop, Flume, Pig, HBase, Phoenix, Oozie, Falcon, Kafka, Storm, Spark, MySQL and Java.

Leave a comment

Your email address will not be published. Required fields are marked *


Review Comments
default image

I am a plsql developer. Intrested to move into bigdata.

Neetika Singh ITA Hadoop in Dec/2016 December 22, 2016

.