DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • Comparing Cloud Hosting vs. Self Hosting
  • Java String Templates Today
  • Apache Cassandra With Java: Introduction to UDT
  • Beginner Intro to Real-Time Debugging for Mobile Apps: Tools and Techniques
  1. DZone
  2. Coding
  3. Java
  4. Java File I/O Basics

Java File I/O Basics

Michael Scharhag user avatar by
Michael Scharhag
·
May. 27, 14 · Interview
Like (0)
Save
Tweet
Share
8.94K Views

Join the DZone community and get the full member experience.

Join For Free

Java 7 introduced the java.nio.file package to provide comprehensive support for file I/O. Besides a lot of other functionality this package includes the Files class (if you already use this class you can stop reading here). Files contains a lot of static methods that can be used to accomplish common tasks when working with files. Unfortunately it looks to me that still a lot of newer (Java 7+) code is written using old (pre Java 7) ways of working with files. This does not have to be bad, but it can make things more complex than needed. A possible reason for this might be that a lot of articles and high rated Stackoverflow answers were written before the release of Java 7.

In the rest of this post I will provide some code samples that show how you can accomplish common file related tasks with Java 7 or newer.

Working with files

// Create directories
// This will create the "bar" directory in "/foo"
// If "/foo" does not exist, it will be created first
Files.createDirectories(Paths.get("/foo/bar"));

// Copy a file
// This copies the file "/foo/bar.txt" to "/foo/baz.txt"
Files.copy(Paths.get("/foo/bar.txt"), Paths.get("/foo/baz.txt"));

// Move a file
// This moves the file "/foo/bar.txt" to "/foo/baz.txt"
Files.move(Paths.get("/foo/bar.txt"), Paths.get("/foo/baz.txt"));

// Delete a file
Files.delete(Paths.get("/foo/bar.txt"));

// Delete a file but do not fail if the file does not exist
Files.deleteIfExists(Paths.get("/foo/bar.txt"));

// Check if a file exists
boolean exists = Files.exists(Paths.get("/foo/bar.txt"));

Most methods of Files take one or more arguments of type Path. Path instances represent a path to a file or directory and can be obtained using Paths.get(). Note that most methods shown here also have an additional varargs parameter that can be used to pass additional options.

For example:

Files.copy(Paths.get("/foo.txt"), Paths.get("/bar.txt"), StandardCopyOption.REPLACE_EXISTING);


Iterating through all files within a directory

Files.walkFileTree(Paths.get("/foo"), new SimpleFileVisitor<Path>() {
	@Override
	public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
		System.out.println("file: " + file);
		return FileVisitResult.CONTINUE;
	}
});

Here the visitFile() method will be called for every file within the /foo directory. You can override additional methods of SimpleFileVisitor if you want to track directories too. 

Writing and reading files

// Write lines to file
List<String> lines = Arrays.asList("first", "second", "third");
Files.write(Paths.get("/foo/bar.txt"), lines, Charset.forName("UTF-8"));

// Read lines
List<String> lines = Files.readAllLines(Paths.get("/foo/bar.txt"), Charset.forName("UTF-8"));

The shown methods work with characters. Similar methods are available if you need to work with bytes. 

Conclusion
If you didn't know about java.nio.file.Files you should definitely have a look at the Javadoc method summary. There is a lot of useful stuff inside.

Java (programming language)

Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Comparing Cloud Hosting vs. Self Hosting
  • Java String Templates Today
  • Apache Cassandra With Java: Introduction to UDT
  • Beginner Intro to Real-Time Debugging for Mobile Apps: Tools and Techniques

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: