gpt4 book ai didi

java - java中使用stringtokenizer显示文件中选定的内容

转载 作者:行者123 更新时间:2023-12-01 13:18:36 25 4
gpt4 key购买 nike

任何人都可以建议如何在java中使用string-tokens来读取文件中的所有数据,并仅显示其部分内容。就像,如果我有

apple = 23456, mango = 12345, orange= 76548, guava = 56734

我需要选择apple,并且与apple对应的值应该显示在输出中。

这是代码

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;

public class ReadFile {

public static void main(String[] args) {

try {

String csvFile = "Data.txt";

//create BufferedReader to read csv file
BufferedReader br = new BufferedReader(new FileReader(csvFile));
String line = "";
StringTokenizer st = null;

int lineNumber = 0;
int tokenNumber = 0;

//read comma separated file line by line
while ((line = br.readLine()) != null) {
lineNumber++;

//use comma as token separator
st = new StringTokenizer(line, ",");

while (st.hasMoreTokens()) {
tokenNumber++;

//display csv values
System.out.print(st.nextToken() + " ");
}

System.out.println();

//reset token number
tokenNumber = 0;
}

} catch (Exception e) {
System.err.println("CSV file cannot be read : " + e);
}
}

}

这是我正在处理的文件:

ImageFormat=GeoTIFF
ProcessingLevel=GEO
ResampCode=CC
NoScans=10496
NoPixels=10944
MapProjection=UTM
Ellipsoid=WGS_84
Datum=WGS_84
MapOriginLat=0.00000000
MapOriginLon=0.00000000
ProdULLat=18.54590200
ProdULLon=73.80059300
ProdURLat=18.54653200
ProdURLon=73.90427600
ProdLRLat=18.45168500
ProdLRLon=73.90487900
ProdLLLat=18.45105900
ProdLLLon=73.80125300
ProdULMapX=373416.66169100
ProdULMapY=2051005.23286800
ProdURMapX=384360.66169100
ProdURMapY=2051005.23286800
ProdLRMapX=373416.66169100
ProdLRMapY=2040509.23286800
ProdLLMapX=384360.66169100
ProdLLMapY=2040509.23286800

除此之外,我只需要显示以下内容: 无扫描 无像素 产品ULLat 产品ULLon 产品LRLat 产品LRLon

最佳答案

public class Test {

public String getValue(String str, String strDelim, String keyValueDelim, String key){
StringTokenizer tokens = new StringTokenizer(str, strDelim);
String sentence;

while(tokens.hasMoreElements()){
sentence = tokens.nextToken();
if(sentence.contains(key)){
return sentence.split(keyValueDelim)[1];
}
}
return null;
}

public static void main(String[] args) {
System.out.println(new Test().getValue("apple = 23456, mango = 12345, orange= 76548, guava = 56734", ",", "=", "apple"));

}
}

" I noticed you have edited your question and added your code. for your new version question you can still simply call method while reading the String from the file and get your desire value ! "

关于java - java中使用stringtokenizer显示文件中选定的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22242714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com