1

Code:

public static void createMovie() {
        String fileName = "C:\\Users\\kat7r\\eclipse-workspace\\Final OOPs project\\src\\movielist.txt";
        File movieFile = new File(fileName);
        try {

            Scanner inputStream = new Scanner(movieFile);
            inputStream.next();
            while (inputStream.hasNext()) {
                String movieArgs = inputStream.next();
                String[] splitData = movieArgs.split(",");
                System.out.println(movieArgs);
                //int priority = Integer.parseInt(splitData[0]);
                //System.out.println("Priority: "+priority);
            }

        } catch(FileNotFoundException e) {
            System.out.println("File not found.");

Expected output:

Priority,Name,Genre,Length,Rating

1,Inception,Science Fiction,2.47,8

2,Shawshank Redemption,Drama,2.37,9

3,Coco,Fantasy,1.82,8

4,Lord of the rings,Fantasy,3.8,9

5,Thor: Ragnarok,Fantasy,2.17,8

Actual output;

1,Inception,Science

Fiction,2.47,8

2,Shawshank

Redemption,Drama,2.37,9

3,Coco,Fantasy,1.82,8

4,Lord

of

the

rings,Fantasy,3.8,9

5,Thor:

Ragnarok,Fantasy,2.17,8

Comments:

Essentially the spaces are causing the IDE to start a new line. I tried using .nextLine but that didn't help. Tried going online as well.

Obsidian Age
  • 36,816
  • 9
  • 39
  • 58
astral004
  • 13
  • 3

2 Answers2

2

Did you use :

inputStream.nextLine();
while(inputStream.hasNextLine())
{
   String movieArgs = inputStream.nextLine(); 
   String[] splitData = movieArgs.split(",");
   System.out.println(movieArgs);
}
  • Initially I had used an excel file that I had saved to .csv format and I tried .nextLine but it didn't work. Since then I've switched to a .txt file format and used your suggestion which made the code work. I know this isn't part of the initial question but is there a way to do it with a .csv file? – astral004 Apr 30 '18 at 22:27
  • @astral004 I've never actually heard of a .csv file before but seeing as it's actually a .txt file in the bg (with a very rigid structure), I don't see why it wouldn't work. The same algo should work in either case. – Kiley Campbell Apr 30 '18 at 22:50
1

Since you want to read the whole line of the input, use inputStream.nextLine() instead of inputStream.next(). Refer to this topic.

It works for me:

public static void createMovie() {
    String fileName = "C:\\Movies.txt";
    File movieFile = new File(fileName);
    try {
        Scanner inputStream = new Scanner(movieFile);
        while (inputStream.hasNextLine()) {
            String movieArgs = inputStream.nextLine();
            System.out.println(movieArgs);
        }

    } catch (FileNotFoundException e) {
        System.out.println("File not found.");
    }
    catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
Izi
  • 59
  • 2
  • 12