1,105,644 Community Members

How Do I Read From a Text File?

Member Avatar
JavaPrograms
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

My task is to: Pick 10 of my favourite NBA or NHL players from 2 top teams and display the player name, team name, points, rebounds, and assists for each of them. I then have to store this information as a table in a .txt file (This part is completed).

The number of points, rebounds, and assists for each team should be read from a .txt file and loaded into appropriately named arrays. The name of the file should be entered by the user.

Ok, so I have done my research and made the .txt file but I'm unsure of how to read from a .txt file and load the stats into appropriately named arrays...Any help is kindly appreciated thanks!

I have this much done so far...but I believe it's incorrect... :(

import java.io.*;
import java.util.Scanner;

class CPT {    
 public static void main ( String[] args )throws IOException {  
  
   File nameOfFile = new File("C:/myText.txt");

  System.out.println("Now please enter the location of this text file!\nAn example would be: C:\\Users\\Your Name\\Desktop\\FolderWithTextFile\textfile.txt");
  Scanner userInput = new Scanner(System.in);
  String nameWithLocation = userInput.nextLine();
String stats[] = new String[10];
  //creates a file object that will store the correct location of that file
  File usersFile = new File(nameWithLocation);
 }
}
Member Avatar
stephen84s
Nearly a Posting Virtuoso
1,328 posts since Jul 2007
Reputation Points: 550 [?]
Q&As Helped to Solve: 160 [?]
Skill Endorsements: 13 [?]
Featured
 
1
 

Checkout the Scanner tutorial here: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html , the example mentioned is doing something similar.

Member Avatar
JavaPrograms
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Checkout the Scanner tutorial here: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html , the example mentioned is doing something similar.

Thanks! But that doesn't allow the user to enter where the file is located manually, instead you have to re-type the text file name into the javascript...

Member Avatar
stephen84s
Nearly a Posting Virtuoso
1,328 posts since Jul 2007
Reputation Points: 550 [?]
Q&As Helped to Solve: 160 [?]
Skill Endorsements: 13 [?]
Featured
 
0
 

You already have that part figured out here, in your chunk of code:-

System.out.println("Now please enter the location of this text file!\nAn example would be: C:\\Users\\Your Name\\Desktop\\FolderWithTextFile\textfile.txt");
  Scanner userInput = new Scanner(System.in);
  String nameWithLocation = userInput.nextLine();

'nameWithLocation' already has the path to the file the user specified, you just need that to construct your FileReader object as mentioned in the given tutorial. Just go on and give it a try ...

Member Avatar
David Kroukamp
Newbie Poster
8 posts since Jan 2012
Reputation Points: 1 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
2
 

Hi there,

well see if this helps the below piece of code will call getfilepath() method to ask the user to input the file path then it will parse the name to the readfile() method and the contents of the file will be displayed line by line.

The only thing left for you to do is parse the contents of each line and get what you need and fill the specific array using an if else statement...

Hope this helps.

Kind regards,
David

here is the code:

package javaapplication1;

import java.io.*;
import java.util.Scanner;

/**
 *
 * @author David
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        String filepath =getfilepath();
        readfile(filepath);
        System.exit(0);
    }

    private static String getfilepath() {
        System.out.println("Now please enter the location of this text file!\n"
                + "An example would be: C:\\textfile.txt");
        Scanner userInput = new Scanner(System.in);
        String nameWithLocation = userInput.nextLine();
        return nameWithLocation;

    }

    private static void readfile(String filepath) {
        try {
            // Open the file that is the first 
            // command line parameter
            FileInputStream fstream = new FileInputStream(filepath);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                System.out.println(strLine);
                //you will then check each string in each line for the ones that macth what you want and fill in your 3 arrays accordingly
            }
            //Close the input stream
            in.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}
Member Avatar
JamesCherrill
... trying to help
10,387 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,752 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

Hi David, welcome to DaniWeb.
I know your intentions were good, but we're here to help beginners build their own Java expertise. By posting complete pieces of code you run the risk that people will copy/paste without fully understanding, thus learning nothing (except maybe that it's easier to cheat than to work). It's much better to steer/prompt/guide them to write their own code.

Member Avatar
JavaPrograms
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi there,

well see if this helps the below piece of code will call getfilepath() method to ask the user to input the file path then it will parse the name to the readfile() method and the contents of the file will be displayed line by line.

The only thing left for you to do is parse the contents of each line and get what you need and fill the specific array using an if else statement...

Hope this helps.

Kind regards,
David

here is the code:

package javaapplication1;

import java.io.*;
import java.util.Scanner;

/**
 *
 * @author David
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        String filepath =getfilepath();
        readfile(filepath);
        System.exit(0);
    }

    private static String getfilepath() {
        System.out.println("Now please enter the location of this text file!\n"
                + "An example would be: C:\\textfile.txt");
        Scanner userInput = new Scanner(System.in);
        String nameWithLocation = userInput.nextLine();
        return nameWithLocation;

    }

    private static void readfile(String filepath) {
        try {
            // Open the file that is the first 
            // command line parameter
            FileInputStream fstream = new FileInputStream(filepath);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                System.out.println(strLine);
                //you will then check each string in each line for the ones that macth what you want and fill in your 3 arrays accordingly
            }
            //Close the input stream
            in.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Hey! Thanks a lot! Do you mind explaining what this line does?

System.exit(0);
Member Avatar
JamesCherrill
... trying to help
10,387 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,752 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

Abruptly terminates the program, sending a return code of 0 to the operating system. Often used to end a program, but does have dangers in that it doesn't allow other parts of the program to close or free any resources they may have open.
In this particular case it's not needed, because the program will terminate normally at the end of the main method anyway.

Member Avatar
JavaPrograms
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Abruptly terminates the program, sending a return code of 0 to the operating system. Often used to end a program, but does have dangers in that it doesn't allow other parts of the program to close or free any resources they may have open.
In this particular case it's not needed, because the program will terminate normally at the end of the main method anyway.

Thanks! I had it removed and it was working properly. When I try running his code I get an error message saying (The system cannot find the path specified). Any clue why it says this?

Member Avatar
David Kroukamp
Newbie Poster
8 posts since Jan 2012
Reputation Points: 1 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
1
 

Thanks! I had it removed and it was working properly. When I try running his code I get an error message saying (The system cannot find the path specified). Any clue why it says this?

Do you mean as you execute it or when you type the path to your file?

if its when you type the path to your file it might be due the fact that either you typed it incorrectly, it had white spaces or its just doesn't exist. put your file in 'c:\\' its easy and no mistakes

Member Avatar
JamesCherrill
... trying to help
10,387 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,752 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
1
 

Probably there was something wrong with the file path/name that you typed in.
You could print out the user's input so you have a record of what the path/file name were.
Rather than using
System.err.println("Error: " + e.getMessage());
in your catch block, use
e.printStackTrace();
which will give you much more info on exactly what and where the problem was.

Member Avatar
David Kroukamp
Newbie Poster
8 posts since Jan 2012
Reputation Points: 1 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
1
 

Abruptly terminates the program, sending a return code of 0 to the operating system. Often used to end a program, but does have dangers in that it doesn't allow other parts of the program to close or free any resources they may have open.
In this particular case it's not needed, because the program will terminate normally at the end of the main method anyway.

Sorry James, i just know how frustrating it is when code doesn't work, I did the complete program but after reading this wont post it thank you and hope to have a great time at www.daniweb.com :)

Member Avatar
JavaPrograms
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Do you mean as you execute it or when you type the path to your file?

if its when you type the path to your file it might be due the fact that either you typed it incorrectly, it had white spaces or its just doesn't exist. out your file in c:\\ its easy and no mistakes

Well...I'm typing it in correctly, and yes it does contain spaces due to the fact that the username contains spaces, and so does "My Documents"...I have to keep it sourced in My Documents.

Member Avatar
David Kroukamp
Newbie Poster
8 posts since Jan 2012
Reputation Points: 1 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
1
 

Well...I'm typing it in correctly, and yes it does contain spaces due to the fact that the username contains spaces, and so does "My Documents"...I have to keep it sourced in My Documents.

Then try using quotes i.e "C:\\test me\\table.txt" or try C:\test me\table.txt . no double backslashes

Member Avatar
JamesCherrill
... trying to help
10,387 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,752 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

... and hope to have a great time at www.daniweb.com :)

I'm sure you will. You contributions are very welcome.. Thanks for helping.

Member Avatar
JavaPrograms
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Probably there was something wrong with the file path/name that you typed in.
You could print out the user's input so you have a record of what the path/file name were.
Rather than using
System.err.println("Error: " + e.getMessage());
in your catch block, use
e.printStackTrace();
which will give you much more info on exactly what and where the problem was.

Oh yea that worked :)Thanks buddy!

Member Avatar
David Kroukamp
Newbie Poster
8 posts since Jan 2012
Reputation Points: 1 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

Oh yea that worked :)Thanks buddy!

Its a pleasure JavaPrograms, when your problem is solved please mark this thread as solved too.

Question Answered as of 2 Years Ago by David Kroukamp, JamesCherrill and stephen84s
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: