[英]Read specific data from a .txt file JAVA
我有個問題。 我正在嘗試讀取一個大的 .txt 文件,但我不需要里面的每一條數據。
我的 .txt 文件看起來像這樣:
8000000 abcdefg hijklmn word word 字母
我只需要數字和前兩個文本位置:“abcdefg”和“hijklmn”,然后將其寫入另一個文件。 我不知道如何讀寫我需要的數據。
到目前為止,這是我的代碼:
BufferedReader br = new BufferedReader(new FileReader("position2.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("position.txt"));
String line;
while ((line = br.readLine())!= null){
if(line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")){
continue;
}else{
//bw.write(line + "\n");
String[] data = line.split(" ");
bw.write(data[0] + " " + data[1] + " " + data[2] + "\n");
}
}
br.close();
bw.close();
}
你能給我一些建議嗎? 提前致謝
更新:我的 .txt 文件有點奇怪。 當它們之間只有一個“”時,使用上面的代碼效果很好。 我的文件可以有一個 \\t 或更多的空格,或者一個 \\t 和單詞之間的一些空格。 我現在可以繼續嗎?
根據數據的復雜性,您有幾種選擇。
如果這些行是簡單的空格分隔值,如所示,最簡單的方法是拆分文本,然后將要保留的值寫入新文件:
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
if (values.length >= 3)
bw.write(values[0] + ' ' + values[1] + ' ' + values[2] + '\n');
}
}
如果值可能更復雜,您可以使用正則表達式:
Pattern p = Pattern.compile("^(\\d+ \\w+ \\w+)");
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
Matcher m = p.matcher(line);
if (m.find())
bw.write(m.group(1) + '\n');
}
}
這確保第一個值僅是數字,第二個和第三個值僅是單詞字符 ( az AZ _ 0-9
)。
else {
String[] res = line.split(" ");
bw.write(res[0] + " " + res[1] + " " + res[2] + "\n"); // the first three words...
}
假設您的文本文件的所有行都遵循您描述的結構,那么您可以這樣做:將 FILE_PATH 替換為您的實際文件路徑。
public static void main(String[] args) {
try {
Scanner reader = new Scanner(new File("FILE_PATH/myfile.txt"));
PrintWriter writer = new PrintWriter(new File("FILE_PATH/myfile2.txt"));
while (reader.hasNextLine()) {
String line = reader.nextLine();
String[] tokens = line.split(" ");
writer.println(tokens[0] + ", " + tokens[1] + ", " + tokens[2]);
}
writer.close();
reader.close();
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
你會得到類似的東西:word0, word1, word2
如果您的文件非常大(可能超過 50-100 MB,可能是 GB)並且您確定第一個單詞是一個數字,並且之后需要兩個單詞,我建議您閱讀一行並遍歷該字符串。 當你找到第三個空間時停止。
String str = readLine();
int num_spaces = 0, cnt = 0;
String arr[] = new String[3];
while(num_spaces < 3){
if(str.charAt(cnt) == ' '){
num_space++;
}
else{
arr[num_space] += str.charAt(cnt);
}
}
如果您的數據只有幾 MB 或里面有很多數字,則無需擔心逐字符迭代。 只需read line by line and split lines then check the words
提到read line by line and split lines then check the words
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.