如何从Java中的文件中读取数字?

时间:2013-03-01 12:54:29

标签: java file java.util.scanner

我正在尝试读取文件,我已经设法读取名称而不是名称后面的数字。我需要将这些数字变成字符串,而不是浮点数或双精度数。更糟糕的是,我必须阅读两个数字。请帮忙吗? (顺便说一句,我输入了必要的代码)

我必须阅读的一个例子:

麦克唐德的农场,118.8 45670

public class Popcorn{ 


public static void main (String [] args) throws IOException { 


             System.out.println("Enter the name of the file");
           Scanner in = new Scanner(System.in);
           String filename = in.next(); 
            Scanner infile = new Scanner(new FileReader( filename)); // 
            String line = "" ; 

           //to get stuff from the file reader

            while (infile.hasNextLine())
            {  line= infile.nextLine(); 

             // int endingIndex =line.indexOf(','); 
           // String fromName = line.substring(0, endingIndex); //this is to get the name of the farm 
           // if (fromName.length()>0){
           //   System.out.println (fromName);
          //  }
           // else if (fromName.length()<= 0)
            //  System.out.println(""); some of the durdling that goes on 
           // }
          while (infile.hasNextLine())
            {  
             line= infile.nextLine().trim();  // added the call to trim to remove whitespace
               if(line.length() > 0)    // test to verify the line isn't blank
               { 
                int endingIndex =line.indexOf(','); 
              String fromName = line.substring(0, endingIndex);
                 String rest = line.substring(endingIndex + 1);
               //   float numbers = Float.valueOf(rest.trim()).floatValue();
    Scanner inLine = new Scanner(rest);

               System.out.println(fromName);
              }
 }
  }
}
}

1 个答案:

答案 0 :(得分:1)

我不知道你的传入文件是什么样的,但是给出了“McDonlad's Farm,118.8 45670”这个例子你可以做到以下几点:

...
String rest = line.substring(endingIndex + 1);
String[] sValues = rest.split("[ \t]"); // split on all spaces and tabs
double[] dValues = new double[sValues.length];
for(int i = 0; i < sValues.length; i++) {
    try {
        dValues[i] = Double.parseDouble(sValues[i]);
    } catch (NumberFormatException e) {
        // some optional exceptionhandling if it's not 
        // guaranteed that all last fields contain doubles
    }
}
...

dValues - 数组应包含所有所需的double(或float)值。

一些额外的注意事项:除了jlordo已经说过的话,如果使用正确的缩进,你的代码会变得更加愉快......