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

DeeKay June 10, 2012 at 11:52 pm ·

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) All Rights Reserved.
package com.kodehelp.javaio;


 * Created by
 * 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";

        File file = new File(filePath);