TEXTFILE
[第1行] a=5
[第2行] b=2
[第3行] c=3
[第4行] a+b*c
我想阅读并仅输出第4行。如何?
而且,我想阅读并将那些a = 5,b = 2,c = 3传递给整数值(变量)
public static void main(String[] args) throws IOException {
try {
File file = new File("D:\\TextFile.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
fileReader.close();
String input = stringBuffer.toString();
String output;
InToPost theTrans = new InToPost(input);
output = theTrans.doTrans();
System.out.println("Postfix is: " + output + '\n');
} catch (IOException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
您可能想尝试apache commons库:
String expression = FileUtils.readLines("D:\\TextFile.txt").get(3);
效率不高,但API看起来很优雅。
答案 1 :(得分:0)
非常简单的方式:
public static void main(String[] args)
throws IOException {
try { File file = new File("D:\\TextFile.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
int lineNumber=0;
Map<String,Integer> valueMap=new HashMap<String,Integer>();
while ((line = bufferedReader.readLine()) != null&& ++lineNumber<4) {
String[] sArr=line.split("=");
//Here you have the number, do whatever you want with it.
Integer iNumber=Integer.parseInt(sArr[1]);
valueMap.put(sArr[0],iNumber);
}
String expression = bufferedReader.readLine();//Read 4th line, expression, delimited by space
String[] sArr=input.split(" ");
int operand1=valueMap.get(sArr[0]);
int operand2=valueMap.get(sArr[2]);
int operand3=valueMap.get(sArr[3]);
char operator1=sArr[1].charAt(0);
char operator2=sArr[1].charAt(0);
// Now Calculate and output.
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
答案 2 :(得分:0)
这就像语言处理一样,纯粹解析数据并处理相同的数据。 我不会为您提供代码,但是想提供一种算法并且很乐意看到您实现它。
Integer.parseInt()
(对于整数值)和Double.parseDouble()
(对于double值)解析值并存储在局部变量中。 (提示:See here)我希望这适合你。