Getting started with Java LanguageInheritanceStreamsExceptions and exception handlingCollectionsLambda ExpressionsGenericsFile I/OArraysInterfacesMapsStringsInputStreams and OutputStreamsDefault MethodsClasses and ObjectsBasic Control StructuresConcurrent Programming (Threads)Console I/OSingletonsVisibility (controlling access to members of a class)Regular ExpressionsAutoboxingDocumenting Java CodeExecutor, ExecutorService and Thread poolsObject Class Methods and ConstructorJAXBPrimitive Data TypesNetworkingOptionalEnumsHttpURLConnectionAnnotationsAudioDate ClassCalendar and its SubclassesNashorn JavaScript engineJava Native InterfaceRemote Method Invocation (RMI)Iterator and IterableOperatorsAssertingScannerProperties ClassPreferencesReflection APIConstructorsByteBufferSerializationJSON in JavaRandom Number GenerationRecursionPolymorphismStringBuilderReference Data TypesBit ManipulationJava AgentsEncapsulationType ConversionBigIntegerBigDecimalRSA EncryptionVarargs (Variable Argument)ThreadLocalLogging (java.util.logging)Using the static keywordDisassembling and DecompilingResources (on classpath)log4j / log4j2JVM FlagsOracle Official Code StandardCharacter encodingJava Memory ManagementImmutable ObjectsObject CloningAlternative CollectionsListsBufferedWriterLocalTimeSetsComparable and ComparatorJVM Tool InterfaceNested and Inner ClassesApache Commons LangGetters and SettersThe ClasspathBytecode ModificationXML Parsing using the JAXP APIsReference TypesLocalization and InternationalizationJAX-WSXML XPath EvaluationJava Performance TuningParallel programming with Fork/Join frameworkCommon Java PitfallsNon-Access ModifiersJava Compiler - 'javac'XJCProcessInstalling Java (Standard Edition)Command line Argument ProcessingDates and Time (java.time.*)Fluent InterfaceXOM - XML Object ModelJust in Time (JIT) compilerFTP (File Transfer Protocol)Java Native AccessModulesJava Pitfalls - Exception usageJava Pitfalls - Language syntaxServiceLoaderClassloadersObject ReferencesJava Pitfalls - Performance IssuesCreating Images ProgrammaticallyAppletsNIO - NetworkingNew File I/OSecure objectsJava Pitfalls - Threads and ConcurrencySplitting a string into fixed length partsJava Pitfalls - Nulls and NullPointerExceptionSecurityManagerJNDIsuper keywordThe java.util.Objects ClassThe Java Command - 'java' and 'javaw'Atomic TypesJava Floating Point OperationsConverting to and from Stringssun.misc.UnsafeJava Memory ModelJava deploymentJava plugin system implementationsQueues and DequesRuntime CommandsNumberFormatSecurity & CryptographyJava Virtual Machine (JVM)Unit TestingJavaBeanExpressionsLiteralsJava SE 8 FeaturesJava SE 7 FeaturesPackagesCurrency and MoneyConcurrent CollectionsUsing ThreadPoolExecutor in MultiThreaded applications.Java Editions, Versions, Releases and DistributionsDynamic Method DispatchJMXSecurity & CryptographyGenerating Java CodeJShellBenchmarksCollection Factory MethodsMulti-Release JAR FilesStack-Walking APITreeMap and TreeSetSocketsJava SocketsUsing Other Scripting Languages in JavaFunctional InterfacesList vs SET2D Graphics in JavaClass - Java ReflectionDequeue InterfaceEnum MapEnumSet classLocal Inner ClassJava Print ServiceImmutable ClassString TokenizerFileUpload to AWSAppDynamics and TIBCO BusinessWorks Instrumentation for Easy IntegrationReaders and WritersHashtableEnum starting with numberSortedMapWeakHashMapLinkedHashMapStringBufferChoosing CollectionsC++ ComparisonCompletableFuture

New File I/O

Other topics

Creating paths

The Path class is used to programmaticaly represent a path in the file system (and can therefore point to files as well as directories, even to non-existent ones)

A path can be obtained using the helper class Paths:

Path p1 = Paths.get("/var/www");
Path p2 = Paths.get(URI.create("file:///home/testuser/File.txt"));
Path p3 = Paths.get("C:\\Users\\DentAr\\Documents\\HHGTDG.odt");
Path p4 = Paths.get("/home", "arthur", "files", "diary.tex");

Retrieving information about a path

Information about a path can be get using the methods of a Path object:

  • toString() returns the string representation of the path

    Path p1 = Paths.get("/var/www"); // p1.toString() returns "/var/www"
    
  • getFileName() returns the file name (or, more specifically, the last element of the path

    Path p1 = Paths.get("/var/www"); // p1.getFileName() returns "www"
    Path p3 = Paths.get("C:\\Users\\DentAr\\Documents\\HHGTDG.odt"); // p3.getFileName() returns "HHGTDG.odt"
    
  • getNameCount() returns the number of elements that form the path

    Path p1 = Paths.get("/var/www"); // p1.getNameCount() returns 2
    
  • getName(int index) returns the element at the given index

    Path p1 = Paths.get("/var/www"); // p1.getName(0) returns "var", p1.getName(1) returns "www"
    
  • getParent() returns the path of the parent directory

    Path p1 = Paths.get("/var/www"); // p1.getParent().toString() returns "/var"
    
  • getRoot() returns the root of the path

    Path p1 = Paths.get("/var/www"); // p1.getRoot().toString() returns "/"
    Path p3 = Paths.get("C:\\Users\\DentAr\\Documents\\HHGTDG.odt"); // p3.getRoot().toString() returns "C:\\"
    

Manipulating paths

Joining Two Paths

Paths can be joined using the resolve() method. The path passed has to be a partial path, which is a path that doesn't include the root element.

Path p5 = Paths.get("/home/");
Path p6 = Paths.get("arthur/files");
Path joined = p5.resolve(p6);
Path otherJoined = p5.resolve("ford/files");
joined.toString() == "/home/arthur/files"
otherJoined.toString() == "/home/ford/files"

Normalizing a path

Paths may contain the elements . (which points to the directory you're currently in) and ..(which points to the parent directory).

When used in a path, . can be removed at any time without changing the path's destination, and .. can be removed together with the preceding element.

With the Paths API, this is done using the .normalize() method:

Path p7 = Paths.get("/home/./arthur/../ford/files");
Path p8 = Paths.get("C:\\Users\\.\\..\\Program Files");
p7.normalize().toString() == "/home/ford/files"
p8.normalize().toString() == "C:\\Program Files"

Retrieving information using the filesystem

To interact with the filesystem you use the methods of the class Files.

Checking existence

To check the existence of the file or directory a path points to, you use the following methods:

Files.exists(Path path)

and

Files.notExists(Path path)

!Files.exists(path) does not neccesarily have to be equal to Files.notExists(path), because there are three possible scenarios:

  • A file's or directory's existence is verified (exists returns true and notExists returns false in this case)
  • A file's or directory's nonexistence is verfied (exists returns false and notExists returns true)
  • Neither the existence nor the nonexistence of a file or a directory can be verified (for example due to access restrictions): Both exists and nonExists return false.

Checking whether a path points to a file or a directory

This is done using Files.isDirectory(Path path) and Files.isRegularFile(Path path)

Path p1 = Paths.get("/var/www");
Path p2 = Paths.get("/home/testuser/File.txt");
Files.isDirectory(p1) == true
Files.isRegularFile(p1) == false

Files.isDirectory(p2) == false
Files.isRegularFile(p2) == true

Getting properties

This can be done using the following methods:

Files.isReadable(Path path)
Files.isWritable(Path path)
Files.isExecutable(Path path)

Files.isHidden(Path path)
Files.isSymbolicLink(Path path)

Getting MIME type

Files.probeContentType(Path path)

This tries to get the MIME type of a file. It returns a MIME type String, like this:

  • text/plain for text files
  • text/html for HTML pages
  • application/pdf for PDF files
  • image/png for PNG files

Reading files

Files can be read byte- and line-wise using the Files class.

Path p2 = Paths.get(URI.create("file:///home/testuser/File.txt"));
byte[] content = Files.readAllBytes(p2);
List<String> linesOfContent = Files.readAllLines(p2);

Files.readAllLines() optionally takes a charset as parameter (default is StandardCharsets.UTF_8):

List<String> linesOfContent = Files.readAllLines(p2, StandardCharsets.ISO_8859_1);

Writing files

Files can be written bite- and line-wise using the Files class

Path p2 = Paths.get("/home/testuser/File.txt");
List<String> lines = Arrays.asList(
    new String[]{"First line", "Second line", "Third line"});

Files.write(p2, lines);
Files.write(Path path, byte[] bytes)

Existing files wile be overridden, non-existing files will be created.

Syntax:

  • Paths.get(String first, String... more) // Creates a Path instance by its String elements
  • Paths.get(URI uri) // Creates a Path instance by a URI

Contributors

Topic Id: 5519

Example Ids: 19625,19626,19627,19628,19629,19630

This site is not affiliated with any of the contributors.