简体   繁体   中英

Reading data from .txt file in java

I have a .txt file in folder conf which contains data as

path = "F://Files//Report.txt" 

name="Henry"

status="1"

I want to read the path of this file in java, and to store that path in another variable in Java. How can I do this? I am new to Java.

Check out Properties . The Properties.load() method has the ability to load a "key=value" formatted file into a map of keys -> values.

You can then access the data like theProperties.getProperty("path") .

Note that you will have to trim leading/trailing double quotes off of the values if the file contains double quotes. For your situation, it is probably sufficient to simply remove all quotes, but it depends on your requirements.

Example: Loading the file:

Properties p = new Properties();
p.load(new FileInputStream("myfile.txt"));
String path = p.getProperty("path");

Example: Removing the double quotes ( path will contain, literally, "F://Files//Report.txt" since that's what it is in the file):

path = path.replace("\"", "");

Note that getProperty() returns null if the property is not found, so you will want to prepare for that:

String path = p.getProperty("path");
if (path != null)
    path = path.replace("\"", "");

Also note that this is a very naive way to remove double quotes (it will mercilessly remove all double quotes, not just ones at the beginning or end) but is probably sufficient for your needs.

You can use property file to simplify your task:

Set values in property file at root folder of your project:

Properties prop = new Properties();
OutputStream output = new FileOutputStream("my.properties");
prop.setProperty("path ", "F://Files//Report.txt");
prop.setProperty("name", "Henry");
prop.setProperty("status", "1");
prop.store(output, null);

Read values from property file:

Properties prop = new Properties();
FileInputStream fis = new FileInputStream("my.properties");
prop.load(fis);
String path = prop.getProperty("path");
String name = prop.getProperty("name");
String status = prop.getProperty("status");

Update

If you want to use only text file as you mentioned in comments you can try this:

BufferedReader reader = new BufferedReader(new FileReader("c://test.txt"));
String path="";
String line;

while ((line = reader.readLine()) != null) {
    path = line;
    path = path.substring(path.indexOf("\""));//get the string after the first occurrence of double quote
    path = path.replace("\"", "").trim();//remove double quotes from string
    break;//read only first line to get path
}
System.out.println(path);

Output:

F://Files//Report.txt

Use java.util.Properties for reading key=value pairs. You can refer this .

Note : Here is a good tutorial to start with.

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