简体   繁体   中英

Read a file using location from properties file

I have one file that is stored in C:/file.txt. The properties file location.properties contains only the path ie C:/file.txt. I want to read the properties file, get the location , read the file and display everything. But I am getting fileNotFound exception. Can anybody help me? This is my code:

package com.tcs.fileRead;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class ReadFile {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Properties prop = new Properties();

        try {

            prop.load(new FileInputStream("location.properties"));
            //prop.load(fileIn);
            String loc = prop.getProperty("fileLoc");
            System.out.println(loc);

            BufferedReader buffer;
            buffer = new BufferedReader(new FileReader(loc));
            String line;
            while((line =buffer.readLine())!= null)
            {
                System.out.println(line);
            }



        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}

This is the output:

"C:\file.txt"
java.io.FileNotFoundException: "C:\file.txt" (The filename, directory name, or volume label syntax is incorrect.)
    at java.io.FileInputStream.<init>(FileInputStream.java:156)
    at java.io.FileInputStream.<init>(FileInputStream.java:111)
    at java.io.FileReader.<init>(FileReader.java:69)
    at com.tcs.fileRead.ReadFile.main(ReadFile.java:29)

您的属性文件中的路径用引号引起来,因此您尝试打开"C:\\file.txt" (这不是有效路径)而不是C:\\file.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM