我有一个.txt文件:
80,90,100,110,120,130,140,150,160
100,20,22,24,26,28,26,28,29,27
110,30,32,34,36,37,39,37,39,40
120,40,41,42,44,45,46,48,47,49
表示百叶窗价格的表格,第一行是百叶窗的宽度,第一列没有80是高度。其余的数字是价格。
我已经使用c#做了这个,但在java中我不知道该怎么做,在c#我的代码看起来像这样,一切都很好。有人能在java中向我展示同样的东西吗? theWidth和theHeight是我必须输入尺寸的文本字段。
string[] lines = File.ReadAllLines(@"tabel.txt");
string[] aux = lines[0].Split(',');
for (int i = 0; i < aux.Length-1; i++)
{
if (aux[i] == theWidth.ToString())
{
Console.WriteLine(aux[i]);
indiceLatime = i;
}
}
for (int i = 1; i < lines.Length; i++)
{
aux = lines[i].Split(',');
if (aux[0] == theHeight.ToString())
{
showPrice.Text = aux[indiceLatime + 1];
}
}
在java中我试过这样的事情:
try {
BufferedReader inputStream = new BufferedReader(new FileReader("tabel.txt"));
int theWidth = 90;
int theHeight = 100;
int indiceLatime = 0;
String line;
try {
while ((line = inputStream.readLine()) != null) {
String[] aux = line.split(",");
for (int i = 0; i < aux.length; i++) {
if (aux[i].equals(Integer.toString(theWidth))) {
indiceLatime = i;
}
}
for (int i = 1; i < aux.length; i++) {
if (aux[0].equals(Integer.toString(theHeight))) {
System.out.println("price: " + aux[indiceLatime]);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
所以价格是在Width指数的高位行,我试图以某种方式获得。是否有人可以告诉我如何从行中获得正确的数字(价格)?
答案 0 :(得分:5)
您可以像这样使用FileReader:
try {
br = new BufferedReader(new FileReader(filePath));
while ((line = br.readLine()) != null) {
// code here to handle the current readed line
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<强> [编辑] 强>
关于您的更新,我已编辑您的代码,请检查。
int widthIndex = 90;
int hightIndex = 100;
int indiceLatime = 0;
boolean lookForWidth = true;
try {
BufferedReader br = new BufferedReader(new FileReader("table.txt"));
String line = "";
while ((line = br.readLine()) != null) {
String[] aux = line.split(",");
if(lookForWidth) {// this flag to look for width only at the first time.
for (int i = 0; i < aux.length; i++) {
if(widthIndex == Integer.parseInt(aux[i].trim())) {
indiceLatime = i;
lookForWidth = false;
continue;
}
}
}
for (int i = 0; i < aux.length; i++) {
if(hightIndex == Integer.parseInt(aux[0])) {
System.out.println(aux[indiceLatime]);
break;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
答案 1 :(得分:1)
试试这样:
public static void main(String[] args) throws FileNotFoundException {
String filePath = <Your file Path>;
try {
BufferedReader br = new BufferedReader(new FileReader(filePath ));
String line = br.readLine();
System.out.println(line);
while (line != null || !line.equals(null)) {
System.out.println(line);
line=br.readLine();
}
} catch (Exception e) {
}
}