[英]How can I get specific information out of a .txt file in java?
我是 Java 新手,我找不到打開文本文件的方法並告訴我的計算機行 1 從 0 到“”它是第一個節點,從“”到“”它是第二個節點,從“ " 到 \\n 這是重量。
這是上述 .txt 文件的摘錄
Eskildstrup 馬里博 28
Eskildstrup NykøbingF 13
Eskildstrup 沃爾丁堡 25
Haslev Korsør 60
Haslev Køge 24
該程序的重點應該是創建一個圖形,然后使用 prim ......這應該不會太難,但我首先很難進行排序......
我有一些關於我如何在 C++ 上做到的例子:
while(std::getline(game, s))
{
std::string n=s.substr(0,s.find("="));
if(n==m_nom)
{
existe=true;
std::string m=s.substr(s.find("=")+1,100000000);
std::string o=m.substr(0, m.find(";"));
std::string coin=m.substr(m.find(";")+1, 100000000);
std::cout<< o<<std::endl<<coin<<std::endl;
std::string delimiter = ",";
或者
for (int i = 0; i < m_ordre; i++)
{
int tempId=0;
std::string tempNom;
double tempAltitude=0;
ifs >> tempId >> tempNom >> tempAltitude;
m_stations.push_back(new Sommet(tempId, tempNom, tempAltitude));
}
但我似乎無法在 Java 中做同樣的事情。 現在,我有我的節點、頂點和圖類。
這就是我的圖形類的樣子 rn...
class Graph
{
public Graph(File doc){
try {
BufferedReader br= new BufferedReader(new FileReader(doc));
String s, line, unique, del=" ";
while ((s= br.readLine())!= null)
System.out.println(s);
while () {
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
一種非常基本的方法,但可能就足夠了:
以下示例將java.nio.Path
和java.nio.Files
用於上述操作 1. 和 2.:
public static void main(String[] args) throws IOException {
String fileLocation = "/path/to/your/graph-coords.txt";
// create a Path from the String
Path filePath = Paths.get(fileLocation);
// if everything is fine with the file (checks omitted for brevity), read its lines
List<String> lines = Files.readAllLines(filePath);
// then handle each line:
lines.forEach(line -> {
// split each line by an arbitrary number of whitespaces
String[] lineValues = line.split("\\s+");
// and do what you want with the results, e.g. create an edge of the graph
System.out.println(lineValues[0] + " --" + lineValues[2] + "km--> " + lineValues[1]);
});
}
這段代碼的輸出是
Eskildstrup --28km--> Maribo
Eskildstrup --13km--> NykøbingF
Eskildstrup --25km--> Vordingborg
Haslev --60km--> Korsør
Haslev --24km--> Køge
作為處理值的示例,我只是將它們重新排列為不同的String
假設重量是以公里為單位的距離。 將文件的所有行放在一個Collection
使得檢查換行符變得過時(這個庫的一個非常方便的東西)。
根據您的計算機系統創建初始String
,我使用了 Linux/MacOs 樣式的路徑,在 Windows 上,我認為您必須提供驅動器號。
此答案僅顯示如何讀取行並將它們拆分為單個值。 它不檢查文件的存在或讀取訪問權限,盡管可以使用java.nio
(例如java.nio.Files.isRegularFile(Path filePath)
或java.nio.Files.isReadable(Path filePath)
和java.nio.Files.exists(Path filePath)
)。 Exception
處理是強制性的,這里我只是讓main
方法throw
一個IOException
來編譯代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.