Last week we looked at how to manipulate files
using a bunch of classes in Java.nio.file.
This week we will learn how to read and write text files using classes
in Java.nio.file package.
- Create
a directory called “files” in the root folder of the project.
- Create
a text file called “source.txt” in the files folder.
- Create
two Path object to hold the source path (“files/source.txt”) and the
target path (“files/target.txt”)
- Create
a Charset object as shown below:
Charset
charset = Charset.forName(“US-ASCII”);
- Within
a try-with-resources block, create a BufferedReader object using the
newBufferedReader method of the Files class passing source path and
charset as parameters.
- In
the try-with-resources block that you created before, add a BufferedWriter
object using
Files.newBufferedWriter method passing target path and charset as
parameter.
- Read
using the BufferedReader’s readLine method and write to target path using
BufferedWriter’s append method.
- Create
two new directories in files directory called “backup” and “work”.
- Copy
the “source.txt” and “target.txt”
to backup folder as “sourceBk.txt” and “targetBk.txt”
- Then,
move the “source.txt” and “target.txt” to “files/work” folder.
- Create
a path for the “files” directory that you created in root directory of the
project.
- Create
a class called FileLister that extends SimpleFileVisitor class. Change the
generic data type to Path.
- Override
all the methods in the SimpleFileVisitor class to create the following
output to the console when you call Files.walkFileTree() passing directory
path and an instance of FileLister.
files <dir>
backup <dir>
sourceBk.txt
targetBk.txt
work <dir>
source.txt
Target.txt
|
- Create
a class called FileSearcher that extends SimpleFileVisitor class. Change
the generic data type to Path.
- Create
a variable called matcher of type PathMatcher
- Create
a constructor for FileSearcher class that accepts a string parameter.
public FileSearcher(String pattern) {
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
- Override
visitFile method of the SimpleFileVisitor. Use matcher.matches() to check
if the file being visited matches the pattern. If there is a match then
add the path to an ArrayList.
- Add
a getter method for the arrayList called getMatchFound();
- In
the main method create an instance of
FileSearcher, pass a pattern (for example: “*.txt”) through the
constructor. Walk the file tree.
- List
the matches found to the console.
files <dir>
backup <dir>
sourceBk.txt
targetBk.txt
work <dir>
source.txt
target.txt
Following matches
were found:
files\backup\sourceBk.txt
files\backup\targetBk.txt
files\work\source.txt
files\work\target.txt
|
- Submit
a screenshot of the entire source code and the output.
Comments
Post a Comment