简体   繁体   中英

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:

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(",", ""));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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