简体   繁体   English

Java程序,用于从文件读取数据并以预定义格式显示

[英]Java program for reading data from file and display in predefined format

I have a text file which is in the following format: 我有一个以下格式的文本文件:

one,
two,
tree,
four,
five,
six,
......and so on

Now I need a Java program which produce output in the following format: 现在,我需要一个Java程序,该程序以以下格式产生输出:

number is one and number is two
number is two and number is three
number is three and number is four
number is five and number is six
......and so on

I tried it to do in various ways but could not get the correct output. 我尝试以各种方式执行此操作,但是无法获得正确的输出。

My code is: 我的代码是:

public static void readData() {
    // TODO Auto-generated method stub
    File f=new File("test.txt");
    try {
        FileReader fileReader=new FileReader(f);
        BufferedReader bufferedReader=new BufferedReader(fileReader);
        String line;
        while((line=bufferedReader.readLine())!=null)
        {
            String line1[] = line.split(",");
            System.out.println("Number is : "+line1[0]+" and Number is :"+line1[1]);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

Following code can help you - 以下代码可以帮助您-

List<String> list = Files.readAllLines(Paths.get("FILE_PATH"));
    for (int i = 1; i < list.size(); i++) {
        System.out.println(
                "number is " + list.get(i - 1).replace(",", "") + " and number is " + list.get(i).replace(",", ""));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM