[英]Reading data from .txt file in java
我在文件夾conf中有一個.txt文件,其中包含數據
path = "F://Files//Report.txt"
name="Henry"
status="1"
我想在java中讀取此文件的路徑,並將該路徑存儲在Java中的另一個變量中。 我怎樣才能做到這一點? 我是Java新手。
查看Properties
。 Properties.load()
方法能夠將“key = value”格式的文件加載到keys - > values的映射中。
然后,您可以訪問類似theProperties.getProperty("path")
。
請注意,如果文件包含雙引號,則必須從值中修剪前導/尾隨雙引號。 對於您的情況,僅刪除所有引號可能就足夠了,但這取決於您的要求。
示例:加載文件:
Properties p = new Properties();
p.load(new FileInputStream("myfile.txt"));
String path = p.getProperty("path");
示例:刪除雙引號( path
將包含字面上的"F://Files//Report.txt"
因為它就是文件中的內容):
path = path.replace("\"", "");
請注意,如果找不到該屬性, getProperty()
將返回null
,因此您需要為此做好准備:
String path = p.getProperty("path");
if (path != null)
path = path.replace("\"", "");
另請注意,這是一種非常天真的刪除雙引號的方法(它將無情地刪除所有雙引號,而不僅僅是開頭或結尾處的雙引號),但可能足以滿足您的需要。
您可以使用屬性文件來簡化任務:
在項目的根文件夾中的屬性文件中設置值:
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);
從屬性文件中讀取值:
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");
更新
如果您只想使用評論中提到的文本文件,可以嘗試這樣做:
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);
輸出:
F://Files//Report.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.