如何读取文件,拆分内容并打印?

时间:2014-10-18 13:51:22

标签: java println string-split

我有一个名为“file”的文件,它是一个文本文件(该文件包含1,2,3,4个整数)..现在我想读取这个文件并拆分文件中的值并打印每个值新队。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

试试这个:

public static void main( String args[] )
{
try {
  Scanner sc = new Scanner(new File("number.txt"));
  sc.useDelimiter(",");
  while (sc.hasNextInt()) {
      System.out.println(sc.nextInt());
  }
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (Exception e) {
  e.printStackTrace();
}
}

答案 1 :(得分:0)

public class Main {

    public static void main(String[] str) throws Exception{

        File f = new File("C:\\prince\\temp\\test.txt");
        FileInputStream fis = new FileInputStream(f);

        BufferedReader br = new BufferedReader(new InputStreamReader(fis));

        String line = null;

        while ((line = br.readLine()) != null) {
            String[] splitedTokens = line.split("[,]");
            for (String splitedToke : splitedTokens) {
                System.out.println(splitedToke);
            }
        }


    }
}