Construct File Path In Java

Construct File Path In Java

Problem statement: How to construct file path in Java IO?

Construct File Path In Java

Construct File Path In Java

Description

To construct file path using Java IO classes like  File.separator, File.createNewFile.

Code

package com.stixs.java.io;
 
import java.io.File;
import java.io.IOException;
 
public class STXCreateFilePath {
 public static void main(String[] args) {
   try {
         String filename = "newSampleFile.txt";
         String stixsWorkingDirectory = "c:\\technostixs\\java";
          
         // File.separator - on Microsoft Windows systems it is '\\'. 
         String absoluteFilePath = stixsWorkingDirectory + File.separator + filename;
 
         System.out.println("STXCreateFilePath:: New file will be created @ " + absoluteFilePath);
 
         //Creates a new File instance by converting the given pathname string into an abstract pathname.
         File file = new File(absoluteFilePath);
 
         //Atomically creates a new, empty file named by this abstract pathname if and only if a 
         //file with this name does not yet exist.
         if (file.createNewFile()) {
            System.out.println("STXCreateFilePath:: New File is Created!");
         } else {
            System.out.println("STXCreateFilePath:: File already Exists!");
         }
       } catch (IOException ioException) {
              System.out.println("STXCreateFilePath:: Exception while creating a new file!");
              ioException.printStackTrace();
       }
   }
}

Output:

Case 1: When the program is executed for the first time i.e When no file with name newSampleFile.txt exist in c:\\technostixs\\java 

STXCreateFilePath:: New file will be created @ c:\technostixs\java\newSampleFile.txt
STXCreateFilePath:: New File is Created!

Case 2: When the program is executed for the second time or morei.e When file with name newSampleFile.txt exist in c:\\technostixs\\java

STXCreateFilePath:: New file will be created @ c:\technostixs\java\newSampleFile.txt
STXCreateFilePath:: File already Exists!

 

Java API Classes and Methods used to construct file path

File.separator

FIle Seperator

java.io.File.File

Construct File Path

Construct File Path

File.createNewFile()

Construct File Path

Java File Class, createNewFile()

 

Reference

Refer below path to get the complete details about Java IO File class.

http://docs.oracle.com/javase/8/docs/api/java/io/File.html

——————————————————————————–

You may also like this

——————————————————————————–

About TechnoStixs.com

TechnoStixs

TechnoStixs.com is a dedicated weblog for Java/J2EE and web developers. We take pride in our work. Every publication is carefully analyzed, written and tested to ease the understanding of the topic or subject.

We cover Java Core Technologies, eCommerce, J2EE Frameworks, Web Service, Build Tools, Unit Test Frameworks and Others.

1,899 total views, 1 views today

Add comment