This document summarizes a presentation on the Java NIO.2 API. It begins with an overview of file system paths and the Path class, including how to create, normalize, resolve and compare paths. It then discusses the File class and common file operations like checking file attributes, existence and accessibility. Examples are provided throughout to demonstrate different path and file methods.
All information in a file is always in binary form or a series of ones and zeros. A document includes any file you have created. It can be a true text document, sound file, graphics, images, or any other type of information the computer can create, store, or size from the internet.
Comparative study on the processing of RDF in PHPMSGUNC
Sharing of content on the Web is already possible through other
technologies such as FTP. It is therefore difficult to understand the need for a
single Web-based format when already there are enough formats such as
relational databases with annotated data that can be reused by other systems.
Putting information into RDF files, makes it possible for computer programs to
search, discover, pick up, collect, analyze and process information from the
web. Using RDF, a Web browser should be able to reuse the data, requiring no
additional work on the part of users, and here comes the tricky part to make
easier for web programmers to work with RDF by using some RDF libraries.
External Tables - not just loading a csv fileKim Berg Hansen
Giving an overview of many of the details of the external table syntax in Oracle that enables you from SQL to access files that reside outside the database
This is the presentation I have in OS course. Mainly focus on the linux file system part and only points out the difference about the Windows file system of NTFS, but I have not dig into it.
All information in a file is always in binary form or a series of ones and zeros. A document includes any file you have created. It can be a true text document, sound file, graphics, images, or any other type of information the computer can create, store, or size from the internet.
Comparative study on the processing of RDF in PHPMSGUNC
Sharing of content on the Web is already possible through other
technologies such as FTP. It is therefore difficult to understand the need for a
single Web-based format when already there are enough formats such as
relational databases with annotated data that can be reused by other systems.
Putting information into RDF files, makes it possible for computer programs to
search, discover, pick up, collect, analyze and process information from the
web. Using RDF, a Web browser should be able to reuse the data, requiring no
additional work on the part of users, and here comes the tricky part to make
easier for web programmers to work with RDF by using some RDF libraries.
External Tables - not just loading a csv fileKim Berg Hansen
Giving an overview of many of the details of the external table syntax in Oracle that enables you from SQL to access files that reside outside the database
This is the presentation I have in OS course. Mainly focus on the linux file system part and only points out the difference about the Windows file system of NTFS, but I have not dig into it.
what are python basics.pptx.Join Python training in Chandigarhasmeerana605
The open() function is the gateway to file operations in Python. It creates a file object that offers methods to interact with the file. The mode determines your level of access (read, write, etc). Closing files using close() releases system resources and prevents data corruption.
Text Input / Output: Files, Streams, Standard Library Input / Output Functions, Formatting Input / Output Functions, Character Input / Output Functions, Binary Input / Output: Text versus Binary Streams, Standard Library, Functions for Files, Converting File Type
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
1. Introducing the Java NIO.2
Presenters:
Oscar GardunoOscar Garduno
Matt KravchakMatt Kravchak
Joao FranciscoJoao Francisco
Fadel AdoeFadel Adoe
2. Organization of Talk
1. From Path to File Operations1. From Path to File Operations
2. From File Operations to Managing Metadata2. From File Operations to Managing Metadata
3. From Read/Write/Create to Symbolic Links3. From Read/Write/Create to Symbolic Links
4. From Walking the File Tree to Legacy I/O code4. From Walking the File Tree to Legacy I/O code
5. Questions or Worries?5. Questions or Worries?
3. What is a Path?
● Data is stored in easily retrievable ways by a
file system.
– Usually in a tree structure with a root.
● Paths begin at root and follow the sub-
directories until the file is reached.
● Microsoft Windows Ex:
– C:homebillylikeToEatWarmApplePie
● is used to separate directory names in
Windows
– / is used in the Solaris OS
From Path to File OperationsFrom Path to File Operations
5. Relative of Absolute?
● A path is either relative or absolute.
● Absolute Paths always contain the root
element and complete directory list necessary
to find the file.
● Ex Solaris OS:
– homebillylikeToEatWarmApplePie
● Relative Paths need to be combined with
another path to access a file.
● Ex: joe/foo
From Path to File OperationsFrom Path to File Operations
6. Symbolic Links
● Most File System objects are typically files or
directories.
● Some systems also support the notation of
symbolic links.
● Symbolic links are referred to as symlink or a
soft link.
● Symbolic links serve as reference to another
file.
From Path to File OperationsFrom Path to File Operations
7. Path Class
● Introduced in the Java SE 7 release.
● Primary entrypoints of the java.nio.file
package.
● A Path object contains the file name and
directory list used to construct the path, and is
used to examine, locate, and manipulate files.
● Note: Users with pre-JDK7 that use
java.io.File can use the Path class by using
the File.toPath method.
From Path to File OperationsFrom Path to File Operations
8. Path Class Cont'd
● Path uses the Solaris syntax
– (/home/joe/foo)
● In Microsoft Windows, Path uses the Windows
syntax
– (C:homejoefoo).
● You cannot compare a path from Solaris to
paths in Windows even if the directory
structure is identical.
From Path to File OperationsFrom Path to File Operations
9. Path Class Cont'd
● With the Path Class you can:
– Create a Path
– Retrieving Information About a Path
– Removing Redundancies from a Path
– Convert a Path
– Join Two Paths
– Creating a Path Between Two Paths
– Comparing Two Paths
● You can also use the Files class to check the
existence of the file corresponding to the Path
From Path to File OperationsFrom Path to File Operations
10. Creating A Path
● Create a Path object by using one of the following get
methods from the Paths (note the plural) helper class:
– Path p1 = Paths.get("/tmp/foo")
● The Paths.get method is shorthand for the following
code:
– Path p1 =
FileSystems.getDefault().getPath("/tmp/foo");
● The following example creates /u/joe/logs/foo.log
assuming your home directory is /u/joe, or
C:joelogsfoo.log if you are on Windows.
– Path p5 =
Paths.get(System.getProperty("user.home"),"log
s", "foo.log");
From Path to File OperationsFrom Path to File Operations
11. Retrieving Information about a Path
● The highest element in the directory structure
us located at index 0.
● Lowest at index [n-1], where n is the number
of name elements in the Path.
From Path to File OperationsFrom Path to File Operations
12. From Path to File OperationsFrom Path to File Operations
13. From Path to File OperationsFrom Path to File Operations
14. Removing Redundancies From Path
● Many file systems use "." notation to denote the current
directory and ".." to denote the parent directory.
– /home/./joe/foo
– /home/sally/../joe/foo
● The normalize method removes any redundant elements,
which includes any "." or "directory/.." occurrences.
● Note that normalize doesn't check at the file system
when it cleans up a path. It is a purely syntactic
operation.
– To clean up a path while ensuring that the result
locates the correct file, you can use the
toRealPath method.
From Path to File OperationsFrom Path to File Operations
15. Converting a Path
● To convert the path to a string that can be
opened from a browser use toUri method
– Path p1 = Paths.get("/home/logfile");
– // Result is file:///home/logfile
– System.out.format("%s%n", p1.toUri());
● The toAbsolutePath method converts a path to
an absolute path. Returns same object if
already absolute.
– // Converts the input string to a Path object.
– Path inputPath = Paths.get(args[0]);
– Path fullPath = inputPath.toAbsolutePath();
From Path to File OperationsFrom Path to File Operations
16. Converting Path Cont'd
● The toAbsolutePath method converts the
user input and returns a Path that returns
useful values when queried.
● File does not have to exist in order for
toAbsoluteMethod to work.
From Path to File OperationsFrom Path to File Operations
17. Converting a Path Cont'd
● The toRealPath method returns the real path
of an existing file. Operations:
– 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.
From Path to File OperationsFrom Path to File Operations
18. Joining Two Paths
● Resolve method combines paths
● You pass 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.
● Ex:
– // Microsoft Windows
– Path p1 = Paths.get("C:homejoefoo");
– // Result is C:homejoefoobar
– System.out.format("%s%n", p1.resolve("bar"));
From Path to File OperationsFrom Path to File Operations
19. ● Passing an absolute path to the resolve
method returns the passed-in path:
– // Solaris
– Path p1 = Paths.get("/home/joe/foo");
– // Result is /home/joe
– Paths.get("foo").resolve("/home/joe");
From Path to File OperationsFrom Path to File Operations
20. Creating a Path Between Two Paths
● Relativize method constructs a path from one
location in the file system to another location.
– The new path is relative to the original path.
● Ex given joe and sally are nodes that reside at
the same level in the tree structure:
– Path p1 = Paths.get("joe");
– Path p2 = Paths.get("sally");
– // Result is ../sally
– Path p1_to_p2 = p1.relativize(p2);
– // Result is ../joe
– Path p2_to_p1 = p2.relativize(p1);
From Path to File OperationsFrom Path to File Operations
21. Comparing Two Paths
● The Path class supports equals, enabling you
to test two paths for equality.
● The startsWith and endsWith methods enable
you to test whether a path begins or ends with
a particular string.
● Ex:
–
From Path to File OperationsFrom Path to File Operations
22. Useful Methods
● Iterator returns an object that enables you to
iterate over the name elements in the path.
● Ex iteration over a path, printing each name
element:
– Path path = ...;
– for (Path name: path) {
– System.out.println(name); }
● Path also implements the Comparable
interface by using compareTo – useful for
sorting.
From Path to File OperationsFrom Path to File Operations
23. File Operations
● The file class is the other primary entrypoint of
the java.nio.file package.
● This class offers a rich set of static methods
for reading, writing, and manipulating files and
directories.
● The Files methods work on instances of Path
objects.
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
24. Checking a File or Directory
● You have a Path instance representing a file or
directory, but does that file exist on the file system?
Is it readable? Writable? Executable?
● You can do so with exists(Path, LinkOption...) and
the notExists(Path, LinkOption...) methods.
● When you are testing a file's existence, three results
are possible:
● The file is verified to exist.
● The file is verified to not exist.
● The file's status is unknown. This result can occur
when the program does not have access to the file.
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
25. Checking File Accessibility
● To verify that the program can access a file as
needed, you can use the isReadable(Path),
isWritable(Path), and isExecutable(Path) methods.
● Code:
Path file = ...;
boolean isRegularExecutableFile = Files.isRegularFile(file) &
Files.isReadable(file) & Files.isExecutable(file);
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
26. Checking Whether Two Paths Locate the
Same File
● When you have a file system that uses symbolic
links, it is possible to have two different paths that
locate the same file.
● The isSameFile(Path, Path) method compares two
paths to determine if they locate the same file on the
file system.
● Code:
Path p1 = ...;
Path p2 = ...;
if (Files.isSameFile(p1, p2)) {
// Logic when the paths locate the same file}
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
27. Deleting a File or Directory
● You can delete files, directories or links
● With symbolic links, the link is deleted and not the target
of the link. With directories, the directory must be empty,
or the deletion fails.
● The Files class provides two deletion methods.
● The delete(Path) method deletes the file or throws an
exception if the deletion fails.
● The deleteIfExists(Path) method also deletes the file, but
if the file does not exist, no exception is thrown.
● Failing silently is useful when you have multiple threads
deleting files and you don't want to throw an exception
just because one thread did so first.
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
28. Deleting a File or Directory
● Code:
try {
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n",
path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);}
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
29. Deleting a File or Directory
● The deleteIfExists(Path) method also deletes
the file, but if the file does not exist, no
exception is thrown.
● Failing silently is useful when you have
multiple threads deleting files and you don't
want to throw an exception just because one
thread did so first.
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
30. Copying a File or Directory
● You can copy a file or directory by using the copy(Path,
Path, CopyOption...) method.
● The copy fails if the target file exists, unless the
REPLACE_EXISTING option is specified.
● Directories can be copied. However, files inside the
directory are not copied, so the new directory is empty
even when the original directory contains files.
● When copying a symbolic link, the target of the link is
copied.
● If you want to copy the link itself, and not the contents of
the link, specify either the NOFOLLOW_LINKS or
REPLACE_EXISTING option.
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
31. Moving a File or Directory
● You can move a file or directory by using the move(Path,
Path, CopyOption...) method.
● The move fails if the target file exists, unless the
REPLACE_EXISTING option is specified.
● Empty directories can be moved. If the directory is not
empty, the move is allowed when the directory can be
moved without moving the contents of that directory.
● On UNIX systems, moving a directory within the same
partition generally consists of renaming the directory.
● In that situation, this method works even when the
directory contains files.
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
32. Managing Metadata
● The definition of metadata is "data about other
data."
● With a file system, the data is contained in its
files and directories, and the metadata tracks
information about each of these objects.
● Is it a regular file, a directory, or a link? What
is its size, creation date, last modified date, file
owner, group owner, and access permissions?
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
33. Managing Metadata
● A file system's metadata is typically referred to
as its file attributes.
● The Files class includes methods that can be
used to obtain a single attribute of a file, or to
set an attribute.
● http://docs.oracle.com/javase/tutorial/essential/io/f
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
34. Managing Metadata
● If a program needs multiple file attributes around the same
time, it can be inefficient to use methods that retrieve a single
attribute.
● Repeatedly accessing the file system to retrieve a single
attribute can adversely affect performance.
● For this reason, the Files class provides two readAttributes
methods to fetch a file's attributes in one bulk operation.
● readAttributes(Path, String, LinkOption...) Reads a file's
attributes as a bulk operation. The String parameter identifies
the attributes to be read.
● readAttributes(Path, Class<A>, LinkOption...) Reads a file's
attributes as a bulk operation. The Class<A> parameter is the
type of attributes requested and the method returns an object
of that class.
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
35. Managing Metadata
● Different file systems have different notions
about which attributes should be tracked.
● For this reason, related file attributes are
grouped together into views.
● A view maps to a particular file system
implementation, such as POSIX or DOS, or to
a common functionality, such as file
ownership.
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
36. Managing Metadata
● BasicFileAttributeView – Provides a view of basic attributes that are required to be
supported by all file system implementations.
● DosFileAttributeView – Extends the basic attribute view with the standard four bits
supported on file systems that support the DOS attributes.
● PosixFileAttributeView – Extends the basic attribute view with attributes supported
on file systems that support the POSIX family of standards, such as UNIX. These
attributes include file owner, group owner, and the nine related access permissions.
● FileOwnerAttributeView – Supported by any file system implementation that
supports the concept of a file owner.
● AclFileAttributeView – Supports reading or updating a file's Access Control Lists
(ACL). The NFSv4 ACL model is supported. Any ACL model, such as the Windows
ACL model, that has a well-defined mapping to the NFSv4 model might also be
supported.
● UserDefinedFileAttributeView – Enables support of metadata that is user defined.
This view can be mapped to any extension mechanisms that a system supports. In
the Solaris OS, for example, you can use this view to store the MIME type of a file.
From File Operations to Managing MetadataFrom File Operations to Managing Metadata
38. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Common Methods for Small Files
● READING ALL BYTES OR LINES FROM A FILE:
Use readAllBytes(Path) or readAllLines(Path, Charset)
Path file = ...;
byte[] fileArray;
fileArray =
Files.readAllBytes(file);
● WRITING ALL BYTES OR LINES FROM A FILE:
Use write(Path, byte[], OpenOption...) or write(Path, Iterable<
extends CharSequence>, Charset, OpenOption...)
Path file = ...;
byte[] fileArray;
fileArray =
Files.readAllBytes(file);
39. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Common Methods for Text Files (Buffered Streams)
● ADVANTAGES: supports channel I/O, which moves data in buffer
(can be faster overall)
● READING A FILE:
Use readAllBytes(Path) or readAllLines(Path, Charset)
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(file,
charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
40. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Common Methods for Text Files (Buffered Streams)
● ADVANTAGES: supports channel I/O, which moves data in buffer
(can be faster overall)
● WRITING A FILE:
Use newBufferedWriter(Path, Charset, OpenOption...)
Charset charset = Charset.forName("US-ASCII");
String s = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, charset))
{
writer.write(s, 0, s.length());
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
41. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Common Methods for Unbuffered Streams
● READING A FILE:
Use newInputStream(Path, OpenOption...)
Path file = ...;
try (InputStream in = Files.newInputStream(file);
BufferedReader reader =
new BufferedReader(new InputStreamReader(in))) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.println(x);
}
42. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Common Methods for Unbuffered Streams
● WRITING A FILE:
Use newOutputStream(Path, OpenOption...)
Path logfile = ...;
// Convert the string to a
// byte array.
String s = ...;
byte data[] = s.getBytes();
try (OutputStream out = new BufferedOutputStream(
logfile.newOutputStream(CREATE, APPEND))) {
...
out.write(data, 0, data.length);
} catch (IOException x) {
System.err.println(x);
}
43. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Common Methods for Channels and ByteBuffers
● ADVANTAGES: can read more than 1 character at a time (reads a buffer at a time)
● READING AND WRITING A FILE:
Use newByteChannel(Path, OpenOption...) or newByteChannel(Path, Set<?
extends OpenOption>, FileAttribute<?>...)
// Reading a File
try (SeekableByteChannel sbc = Files.newByteChannel(file)) {
ByteBuffer buf = ByteBuffer.allocate(10);
// Read the bytes with the proper encoding for this platform. If
// you skip this step, you might see something that looks like
// Chinese characters when you expect Latin-style characters.
String encoding = System.getProperty("file.encoding");
while (sbc.read(buf) > 0) {
buf.rewind();
System.out.print(Charset.forName(encoding).decode(buf));
buf.flip();
}
} catch (IOException x) {
System.out.println("caught exception: " + x);
44. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Common Methods for Channels and ByteBuffers
// Create a LOG file
import static java.nio.file.StandardCopyOption.*;
// Create the set of options for appending to the file.
Set<OpenOptions> options = new HashSet<OpenOption>();
options.add(APPEND);
options.add(CREATE);
// Create the custom permissions attribute.
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rw-r------");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
// Convert the string to a ByteBuffer.
String s = ...;
byte data[] = s.getBytes();
ByteBuffer bb = ByteBuffer.wrap(data);
try (SeekableByteChannel sbc = Files.newByteChannel(file, options, attr)) {
sbc.write(bb);
} catch (IOException x) {
System.out.println("exception thrown: " + x);
}
45. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Creating Files
● CREATING AN EMPTY FILE: (Atomic Operation)
Use createFile(Path, FileAttribute<?>)
Path file = ...;
try {
// Create the empty file with default permissions, etc.
Files.createFile(file);
} catch (FileAlreadyExistsException x) {
System.err.format("file named %s" +
" already exists%n", file);
} catch (IOException x) {
// Some other sort of failure, such as permissions.
System.err.format("createFile error: %s%n", x);
}
46. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Creating Files
● CREATING A TEMPORARY FILE: (Atomic Operation)
Use createTempFile(Path, String, String, FileAttribute<?>) or
createTempFile(String, String, FileAttribute<?>)
try {
Path tempFile = Files.createTempFile(null, ".myapp");
System.out.format("The temporary file" +
" has been created: %s%n", tempFile)
;
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
The result would be something like:
The temporary file has been created:
/tmp/509668702974537184.myapp
47. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Random Access Files
● READING AND WRITING:
Use the SeekableByteChannel interface
String s = "I was here!n";
byte data[] = s.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);
ByteBuffer copy = ByteBuffer.allocate(12);
try (FileChannel fc = (FileChannel.open(file,
READ, WRITE))) {
// Read the first 12
// bytes of the file.
int nread;
do {
nread = fc.read(copy);
} while (nread != -1 &&
copy.hasRemaining());
// Write "I was here!" at the beginning of the
file.
fc.position(0);
while (out.hasRemaining())
fc.write(out);
out.rewind();
// Move to the end of the file. Copy the first
12 bytes to
// the end of the file. Then write "I was
here!" again.
long length = fc.size();
fc.position(length-1);
copy.flip();
while (copy.hasRemaining())
fc.write(copy);
while (out.hasRemaining())
fc.write(out);
} catch (IOException x) {
System.out.println("I/O Exception: " + x);
}
48. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Manipulating Directories
● CREATING A DIRECTORY:
Use createDirectory(Path, FileAttribute<?>)
Path dir = ...;
Files.createDirectory(path);
● LISTING A DIRECTORY'S CONTENTS:
Use newDirectoryStream(Path)
Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file: stream) {
System.out.println(file.getFileName());
}
} catch (IOException | DirectoryIteratorException x) {
// IOException can never be thrown by the iteration.
// In this snippet, it can only be thrown by newDirectoryStream.
System.err.println(x);
}
49. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Symbolic Links
● The java.nio.file package, and the Path class in particular, is "link aware." Every
Path method either detects what to do when a symbolic link is encountered, or it
provides an option enabling you to configure the behavior when a symbolic link is
encountered.
● CREATING A SYMBOLIC LINK:
Use createSymbolicLink(Path, Path, FileAttribute<?>)
Path newLink = ...;
Path target = ...;
try {
Files.createSymbolicLink(newLink, target);
} catch (IOException x) {
System.err.println(x);
} catch (UnsupportedOperationException x) {
// Some file systems do not support symbolic links.
System.err.println(x);
}
50. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Symbolic Links
● CREATING A HARD LINK:
Use createLink(Path, Path)
Path newLink = ...;
Path existingFile = ...;
try {
Files.createLink(newLink, existingFile);
} catch (IOException x) {
System.err.println(x);
} catch (UnsupportedOperationException x) {
// Some file systems do not
// support adding an existing
// file to a directory.
System.err.println(x);
}
51. From Read/Write/Create to Symbolic LinFrom Read/Write/Create to Symbolic Linksks
Symbolic Links
● DETECTING A SYMBOLIC LINK:
Use isSymbolicLink(Path)
Path file = ...;
boolean isSymbolicLink
=
Files.isSymbolicLink(file)
;
● FINDING THE TARGET OF A SYMBOLIC LINK:
Use readSymbolicLink(Path)
Path link = ...;
try {
System.out.format("Target of link" +
" '%s' is '%s'%n", link,
Files.readSymbolicLink(link));
} catch (IOException x) {
System.err.println(x);
}
// If the path is not a link, it throws a NotLinkException
52. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O code
The FileVisitor Interface
1. preVisitDirectory
2. postVisitDirectory
3. visitFile
4. visitFileFailed
53. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O code
The FileVisitor Interface implemented
import static java.nio.file.FileVisitResult.*;
public static class PrintFiles
extends SimpleFileVisitor<Path> {
// Print information about
// each type of file.
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attr) {
if (attr.isSymbolicLink()) {
System.out.format("Symbolic link: %s ", file);
} else if (attr.isRegularFile()) {
System.out.format("Regular file: %s ", file);
} else {
System.out.format("Other: %s ", file);
}
System.out.println("(" + attr.size() + "bytes)");
return CONTINUE;
}
// Print each directory visited.
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException exc) {
System.out.format("Directory: %s%n", dir);
return CONTINUE;
}
// If there is some error accessing
// the file, let the user know.
// If you don't override this method
// and an error occurs, an IOException
// is thrown.
@Override
public FileVisitResult visitFileFailed(Path file,
IOException exc) {
System.err.println(exc);
return CONTINUE;
}
}
54. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O code
Kickstarting the Process
Path startingDir = ...;
PrintFiles pf = new PrintFiles();
Files.walkFileTree(startingDir, pf);
Technical Note:
The tree traversal is depth first search, but subdirectories traversal is non-
deterministic
Controlling the Tree Traversal
import static java.nio.file.FileVisitResult.*;
// The file we are looking for.
Path lookingFor = ...;
public FileVisitResult
visitFile(Path file,
BasicFileAttributes attr) {
if (file.getFileName().equals(lookingFor)) {
System.out.println("Located file: " + file);
return TERMINATE;
}
return CONTINUE;
}
import static java.nio.file.FileVisitResult.*;
public FileVisitResult
preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
(if (dir.getFileName().toString().equals("SCCS")) {
return SKIP_SUBTREE;
}
return CONTINUE;
}
55. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O code
Finding Files
PathMatcher matcher =
FileSystems.getDefault().getPathMatcher("glob:*.{java,class}");
Path filename = ...;
if (matcher.matches(filename)) {
System.out.println(filename);
}
Watching a Directory for Changes: The Watch Service API
1. Create a WatchService "watcher" for the file system.
2. Register Directories with the watcherr.
3. Implement an infinite loop to wait for incoming events. When an event occurs, the key is signaled and placed into the watcher's
queue.
4. Retrieve the key from the watcher's queue. You can obtain the file name from the key.
5. Retrieve each pending event for the key (there might be multiple events) and process as needed.
6Reset the key, and resume waiting for events.
7 Close the service: The watch service exits when either the thread exits or when it is closed (by invoking its closed method).
56. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O code
Watching a Directory for Changes: The Watch Service API
import static java.nio.file.StandardWatchEventKinds.*;
Path dir = ...;
try {
WatchKey key = dir.register(watcher,
ENTRY_CREATE,
ENTRY_DELETE,
ENTRY_MODIFY);
} catch (IOException x) {
System.err.println(x);
}
for (;;) {
// wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
continue;
}
// The filename is the
// context of the event.
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
try {
Path child = dir.resolve(filename);
if (!Files.probeContentType(child).equals("text/plain")) {
System.err.format("New file '%s'" +
" is not a plain text file.%n", filename);
continue;
}
} catch (IOException x) {
System.err.println(x);
continue;
}
System.out.format("Emailing file %s%n", filename);
//Details left to reader....
}
boolean valid = key.reset();
if (!valid) {
break;
}
57. From Walking the File Tree to Legacy I/O codeFrom Walking the File Tree to Legacy I/O code
Interoperability with Legacy Code
Smile :), it is just a single line of code to convert from
java.io.File to java.nio.file
Path nioPath = oldFile.toPath();
Now, continue with your java.nio.path cruise :)
58. What We Told you earlier and wish to tell youWhat We Told you earlier and wish to tell you
Again!Again!
The Path class: use it to manipulate paths
The File class: use it for file operations, such as moving,
coping, deleting, and ...
The FileSystem class: use it to obtain infomation about the file
system