package essentials;
import java.nio.file.Files;
import java.nio.file.Path;
// Not recommended
import static java.lang.String.format;
import static java.lang.System.*; // Not recommended
/**
* This sample prints the current date and all the files in the current
* directory with their size in bytes. It illustrates how can be
* imported.
*
* In Java, the necessary to compile and run a program are made available
* through an environment variable, the , and can be referenced by
* their . In contrast to other languages, in Java it is not
* necessary to add any instruction to the source code to include dependencies.
* However, we can import packages to simplify the names of external types and
* members we wish to reference in our code.
*/
class Importing
{
public static void main(String[] args)
{
System.out.println(new ());
for( fileName : new File(".").list() )
{
.println((, fileName, Files.size(Path.of(fileName))));
}
}
}
Here we mean the public classes, interfaces, and other top-level declarations
defined in external source or binaries files, such as String
or List
.
Here we mean the public classes, interfaces, and other top-level declarations
defined in external source or binaries files, such as String
or List
.
The CLASSPATH
is a setting that specifies where to find the code that a Java program
depends on. It should at the very least include a reference to the Java libraries. When using
an Integrated Development Environment (IDE), the classpath is managed by this environment, and may
therefore not be a persistent environment variable named CLASSPATH
.
The CLASSPATH
is a setting that specifies where to find the code that a Java program
depends on. It should at the very least include a reference to the Java libraries. When using
an Integrated Development Environment (IDE), the classpath is managed by this environment, and may
therefore not be a persistent environment variable named CLASSPATH
.
This string is a format string, which contains specifiers that follow a specified syntax. The specifiers indicate how the following arguments will be processed.
This string is a format string, which contains specifiers that follow a specified syntax. The specifiers indicate how the following arguments will be processed.
The fully-qualified name of a Java type consists of the name of its package
followed by its simple name. For example, the fully-qualified name of
the library type String
is java.lang.String
.
These statements are examples of type imports. They consist of the
of a type. Once a type is imported, it is possible to refer to it by its simple name.
For example, in this source code file, references to type Path
will unambiguously
refer to java.nio.file.Path
.
These statements are examples of type imports. They consist of the
of a type. Once a type is imported, it is possible to refer to it by its simple name.
For example, in this source code file, references to type Path
will unambiguously
refer to java.nio.file.Path
.
The fully-qualified name of a Java type consists of the name of its package
followed by its simple name. For example, the fully-qualified name of
the library type String
is java.lang.String
.
The fully-qualified name of a Java type consists of the name of its package
followed by its simple name. For example, the fully-qualified name of
the library type String
is java.lang.String
.
This statement is an example of a wildcard import, (a.k.a., star import). Its effect is to automatically import
all types in the specified package. Wildcard imports are commonly considered a bad practice because, in part, they
hide the otherwise clear origin of a type. For example, in this sample, two types are declared in package java.io
, but
it might not be clear which two.
This statement is an example of a wildcard import, (a.k.a., star import). Its effect is to automatically import
all types in the specified package. Wildcard imports are commonly considered a bad practice because, in part, they
hide the otherwise clear origin of a type. For example, in this sample, two types are declared in package java.io
, but
it might not be clear which two.
Static fields and methods can be imported
using the static
keyword. Importing a static member
removes the need to specify its declaring type when referring
to it. Like regular type imports, it
is also possible to use a wildcard (*
) to import all
static members for a type, although this practice is discouraged.
In fact, static imports are in general
discouraged.
Static fields and methods can be imported
using the static
keyword. Importing a static member
removes the need to specify its declaring type when referring
to it. Like regular type imports, it
is also possible to use a wildcard (*
) to import all
static members for a type, although this practice is discouraged.
In fact, static imports are in general
discouraged.
This clauses is necessary because we are using a method (File#size
)
that can throw a checked exception. Exceptions are covered in a different
sample.
This clauses is necessary because we are using a method (File#size
)
that can throw a checked exception. Exceptions are covered in a different
sample.
In this statement, the type Date
from package java.util
is
referenced using its fully-qualified name. Types referenced
using their fully-qualified name do not need to be imported.
Date
represents a specific instant in time, with millisecond precision.
Date
object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
In this statement, the type Date
from package java.util
is
referenced using its fully-qualified name. Types referenced
using their fully-qualified name do not need to be imported.
Date
represents a specific instant in time, with millisecond precision.
Prior to JDK 1.1, the class Date
had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar
class should be used to convert between dates and time fields and the DateFormat
class should be used to format and parse date strings. The corresponding methods in Date
are deprecated.
Although the Date
class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.
Some computer standards are defined in terms of Greenwich mean time (GMT), which is equivalent to universal time (UT). GMT is the "civil" name for the standard; UT is the "scientific" name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations, which for all practical purposes is an invisibly fine hair to split. Because the earth's rotation is not uniform (it slows down and speeds up in complicated ways), UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1, which is a version of UT with certain corrections applied. There are other time and date systems as well; for example, the time scale used by the satellite-based global positioning system (GPS) is synchronized to UTC but is not adjusted for leap seconds. An interesting source of further information is the United States Naval Observatory (USNO):
https://www.usno.navy.mil/USNO
and the material regarding "Systems of Time" at:
https://www.usno.navy.mil/USNO/time/master-clock/systems-of-time
which has descriptions of various different time systems including UT, UT1, and UTC.
In all methods of class Date
that accept or return year, month, date, hours, minutes, and seconds values, the following representations are used:
- 1900
. In all cases, arguments given to methods for these purposes need not fall within the indicated ranges; for example, a date may be specified as January 32 and is interpreted as meaning February 1.
Types in the package java.lang
are imported by default. For this reason,
java.lang.String
can be referred to with its simple name without having
to explicitly import it.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Types in the package java.lang
are imported by default. For this reason,
java.lang.String
can be referred to with its simple name without having
to explicitly import it.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2, 3); String d = cde.substring(1, 2);
The class String
includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor or method in this class will cause a NullPointerException
to be thrown.
A String
represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character
class for more information). Index values refer to char
code units, so a supplementary character uses two positions in a String
.
The String
class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator
class provides methods for finer-grain, locale-sensitive String comparison.
javac
compiler may implement the operator with StringBuffer
, StringBuilder
, or java.lang.invoke.StringConcatFactory
depending on the JDK version. The implementation of string conversion is typically through the method toString
, defined by Object
and inherited by all classes in Java.
File
instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.
User interfaces and operating systems use system-dependent pathname strings to name files and directories. This class presents an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:
"/"
for the UNIX root directory, or "\\\\"
for a Microsoft Windows UNC pathname, and The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default separator character. The default name-separator character is defined by the system property file.separator
, and is made available in the public static fields separator
and separatorChar
of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.
A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io
package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir
, and is typically the directory in which the Java virtual machine was invoked.
The parent of an abstract pathname may be obtained by invoking the getParent()
method of this class and consists of the pathname's prefix and each name in the pathname's name sequence except for the last. Each directory's absolute pathname is an ancestor of any File
object with an absolute abstract pathname which begins with the directory's absolute pathname. For example, the directory denoted by the abstract pathname "/usr"
is an ancestor of the directory denoted by the pathname "/usr/local/bin"
.
The prefix concept is used to handle root directories on UNIX platforms, and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms, as follows:
"/"
. Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix "/"
and an empty name sequence. ":"
and possibly followed by "\\"
if the pathname is absolute. The prefix of a UNC pathname is "\\\\"
; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix. Instances of this class may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a partition. A partition is an operating system-specific portion of storage for a file system. A single storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may contain multiple partitions. The object, if any, will reside on the partition named by some ancestor of the absolute form of this pathname.
A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions. The file system may have multiple sets of access permissions on a single object. For example, one set may apply to the object's owner, and another may apply to all other users. The access permissions on an object may cause some methods in this class to fail.
Instances of the File
class are immutable; that is, once created, the abstract pathname represented by a File
object will never change.
java.nio.file
package The java.nio.file
package defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems. This API may be used to overcome many of the limitations of the java.io.File
class. The toPath
method may be used to obtain a Path
that uses the abstract path represented by a File
object to locate a file. The resulting Path
may be used with the Files
class to provide more efficient and extensive access to additional file operations, file attributes, and I/O exceptions to help diagnose errors when an operation on a file fails.
File
instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.
pathname
- A pathname string
NullPointerException
- If the pathname
argument is null
The standard output stream is globally available as System.out
, but here
we can refer to it as out
because it has been statically-imported. This
sample imports System.out
only to illustrate how static imports work. It is
not a recommended practice.
Console.charset()
if the Console
exists, stdout.encoding otherwise.
The standard output stream is globally available as System.out
, but here
we can refer to it as out
because it has been statically-imported. This
sample imports System.out
only to illustrate how static imports work. It is
not a recommended practice.
Console.charset()
if the Console
exists, stdout.encoding otherwise.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println
methods in class PrintStream
.
This identifier refers to method String#format
, which was statically
imported and can thus be referred to as format
.
This identifier refers to method String#format
, which was statically
imported and can thus be referred to as format
.
The locale always used is the one returned by Locale.getDefault(Locale.Category)
with FORMAT
category specified.
format
- A format string
args
- Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java Virtual Machine Specification. The behaviour on a null
argument depends on the conversion.
IllegalFormatException
- If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the formatter class specification.
"A package a grouping of related types providing access protection and name space management." Source code files in a package must be placed in a directory with the same name as the package, and a package declaration must be placed at the top of the file.
"A package a grouping of related types providing access protection and name space management." Source code files in a package must be placed in a directory with the same name as the package, and a package declaration must be placed at the top of the file.
print(String)
and then println()
.
print(String)
and then println()
.
x
- The String
to be printed.
If this abstract pathname does not denote a directory, then this method returns null
. Otherwise an array of strings is returned, one for each file or directory in the directory. Names denoting the directory itself and the directory's parent directory are not included in the result. Each string is a file name rather than a complete path.
There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.
Note that the Files
class defines the newDirectoryStream
method to open a directory and iterate over the names of the files in the directory. This may use less resources when working with very large directories, and may be more responsive when working with remote directories.
null
if this abstract pathname does not denote a directory, or if an I/O error occurs.
SecurityException
- If a security manager exists and its SecurityManager.checkRead(String)
method denies read access to the directory
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2, 3); String d = cde.substring(1, 2);
The class String
includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor or method in this class will cause a NullPointerException
to be thrown.
A String
represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character
class for more information). Index values refer to char
code units, so a supplementary character uses two positions in a String
.
The String
class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator
class provides methods for finer-grain, locale-sensitive String comparison.
javac
compiler may implement the operator with StringBuffer
, StringBuilder
, or java.lang.invoke.StringConcatFactory
depending on the JDK version. The implementation of string conversion is typically through the method toString
, defined by Object
and inherited by all classes in Java.
System
class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System
class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
System
class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System
class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Console.charset()
if the Console
exists, stdout.encoding otherwise.
Console.charset()
if the Console
exists, stdout.encoding otherwise.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println
methods in class PrintStream
.
print(String)
and then println()
.
print(String)
and then println()
.
x
- The Object
to be printed.
A Path
represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter. A root component, that identifies a file system hierarchy, may also be present. The name element that is farthest from the root of the directory hierarchy is the name of a file or directory. The other name elements are directory names. A Path
can represent a root, a root and a sequence of names, or simply one or more name elements. A Path
is considered to be an empty path if it consists solely of one name element that is empty. Accessing a file using an empty path is equivalent to accessing the default directory of the file system. Path
defines the getFileName
, getParent
, getRoot
, and subpath
methods to access the path components or a subsequence of its name elements.
In addition to accessing the components of a path, a Path
also defines the resolve
and resolveSibling
methods to combine paths. The relativize
method that can be used to construct a relative path between two paths. Paths can be compared
, and tested against each other using the startsWith
and endsWith
methods.
This interface extends Watchable
interface so that a directory located by a path can be registered
with a WatchService
and entries in the directory watched.
WARNING: This interface is only intended to be implemented by those developing custom file system implementations. Methods may be added to this interface in future releases.
Paths may be used with the Files
class to operate on files, directories, and other types of files. For example, suppose we want a BufferedReader
to read text from a file "access.log
". The file is located in a directory "logs
" relative to the current working directory and is UTF-8 encoded.
Path path = FileSystems.getDefault().getPath("logs", "access.log");
BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
Paths associated with the default provider
are generally interoperable with the java.io.File
class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented by java.io.File
. The toPath
method may be used to obtain a Path
from the abstract path name represented by a java.io.File
object. The resulting Path
can be used to operate on the same file as the java.io.File
object. In addition, the toFile
method is useful to construct a File
from the String
representation of a Path
.
Implementations of this interface are immutable and safe for use by multiple concurrent threads.
Path
by converting a path string, or a sequence of strings that when joined form a path string. If more
does not specify any elements then the value of the first
parameter is the path string to convert. If more
specifies one or more elements then each non-empty string, including first
, is considered to be a sequence of name elements and is joined to form a path string. The details as to how the Strings are joined is provider specific but typically they will be joined using the name-separator
as the separator. For example, if the name separator is "/
" and getPath("/foo","bar","gus")
is invoked, then the path string "/foo/bar/gus"
is converted to a Path
. A Path
representing an empty path is returned if first
is the empty string and more
does not contain any non-empty strings.
Path
by converting a path string, or a sequence of strings that when joined form a path string. If more
does not specify any elements then the value of the first
parameter is the path string to convert. If more
specifies one or more elements then each non-empty string, including first
, is considered to be a sequence of name elements and is joined to form a path string. The details as to how the Strings are joined is provider specific but typically they will be joined using the name-separator
as the separator. For example, if the name separator is "/
" and getPath("/foo","bar","gus")
is invoked, then the path string "/foo/bar/gus"
is converted to a Path
. A Path
representing an empty path is returned if first
is the empty string and more
does not contain any non-empty strings.
The Path
is obtained by invoking the getPath
method of the default
FileSystem
.
Note that while this method is very convenient, using it will imply an assumed reference to the default FileSystem
and limit the utility of the calling code. Hence it should not be used in library code intended for flexible reuse. A more flexible alternative is to use an existing Path
instance as an anchor, such as:
Path dir = ...
Path path = dir.resolve("file");
first
- the path string or initial part of the path string
more
- additional strings to be joined to form the path string
Path
InvalidPathException
- if the path string cannot be converted to a Path
In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.
regular
files is implementation specific and therefore unspecified.
regular
files is implementation specific and therefore unspecified.
path
- the path to the file
IOException
- if an I/O error occurs
SecurityException
- In the case of the default provider, and a security manager is installed, its checkRead
method denies read access to the file.