Backend Development 7 min read

Using JDK7 Standard Library for Flexible and Secure File Handling in Java

This article demonstrates how to leverage JDK7's standard library—Path, Paths, Files, and FileSystem—to perform flexible file operations, safe path concatenation, size‑checked reading, automatic resource management, directory traversal with FileVisitor, and security measures for preventing unsafe file access.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Using JDK7 Standard Library for Flexible and Secure File Handling in Java

The author writes this blog because many projects contain messy and insecure file‑handling code, and introduces a set of flexible methods for handling files using the JDK7 standard library.

Key utility classes include Path , Paths , Files and FileSystem , which provide a modern API for file operations.

Examples:

// Obtain a Path object Path path = Paths.get("/test/a.txt"); // Convert Path to File File file = path.toFile(); Files.readAllBytes(path); Files.deleteIfExists(path); Files.size(path);

When constructing paths, avoid manual string concatenation. Bad code such as File file = new File("~/test/" + game + ".txt"); can lead to platform‑specific bugs. Instead, use Paths.get with separate path elements:

Path path = Paths.get("~/test/", "foo", "bar", "a.txt"); System.out.println(path); // ~/test/foo/bar/a.txt

To read an entire file safely, first check its size to prevent OutOfMemory errors. Sample utility methods:

public static byte[] readAllBytes(String fileName, long maxSize) throws IOException { Path path = Paths.get(fileName); long size = Files.size(path); if (size > maxSize) { throw new IOException("file: " + path + ", size:" + size + "> " + maxSize); } return Files.readAllBytes(path); } public static List readAllLines(String fileName, Charset charset, long maxSize) throws IOException { Path path = Paths.get(fileName); long size = Files.size(path); if (size > maxSize) { throw new IOException("file: " + path + ", size:" + size + "> " + maxSize); } return Files.readAllLines(path, charset); }

JDK7’s try‑with‑resources simplifies automatic closing of streams:

Path path = Paths.get("~/test/", "foo", "bar", "a.txt"); try (InputStream in = Files.newInputStream(path)) { // process the stream }

Directory traversal can be performed with the FileVisitor API. Example visitor:

public class MyFileVisitor extends SimpleFileVisitor { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { System.out.println(file); return FileVisitResult.CONTINUE; } public static void main(String[] args) throws IOException { Path path = Paths.get("/home/user/test"); Files.walkFileTree(path, new MyFileVisitor()); } }

To verify that a file resides within a given parent directory, compare canonical paths:

public static boolean isSubFile(File parent, File child) throws IOException { return child.getCanonicalPath().startsWith(parent.getCanonicalPath()); } public static boolean isSubFile(String parent, String child) throws IOException { return isSubFile(new File(parent), new File(child)); }

JDK7 also provides a watch service (based on Linux inotify) for monitoring file changes, though its API is more complex.

For web servers, prevent illegal file‑path access such as null‑byte injection (e.g., .../etc/passwd%00.gif ) by checking the file’s parent path before writing and by using Java’s security manager:

// Grant read permission to all files under /img/java grant codeBase "file:/home/programpath/" { permission java.io.FilePermission "/img/java", "read"; };

Tomcat’s security manager can be configured (see the official documentation), and static resources should be served by the container’s default servlet rather than custom code. Example servlet mapping:

<servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/static/*</url-pattern> </servlet-mapping>

Spring MVC can map resources similarly:

<mvc:resources mapping="/resources/**" location="/public-resources/"/> <mvc:default-servlet-handler/>

Using the container’s default servlet (e.g., Tomcat’s) provides better support for ETag, range requests, and caching.

References: Spring MVC documentation, Tomcat source code, and the original CSDN blog post.

backendJavasecurityfile I/OJDK7path
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.