How to Use File Separator to construct file path in java?

Many java developers might have came across the code where the developer need to use file separator for the file path or directory path. Many of them are using “/” or “\” depending upon the operating system. Using the forward or backward slash is not a good practice while coding in the java,¬†because¬†your code may work in one platform but not in other platform.

Below Java code shows how to use File.Separator to construct file path –

/****************************************************************************************
 * Created on 06-2012 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

import java.io.File;

/**
 * Created by http://kodehelp.com
 * Date: 6/10/12
 */
public class FileSeparator {
    public static void main(String args[]){
        String baseFilePath = System.getProperty("user.dir");
        String filePath = baseFilePath + File.separator + "temp" + File.separator +"Sample.txt";

        System.out.println(filePath);
        File file = new File(filePath);
    }
}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.