How Do I Read From a Text File?
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);
}
}
JavaPrograms
Junior Poster in Training
72 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
stephen84s
Nearly a Posting Virtuoso
1,444 posts since Jul 2007
Reputation Points: 668
Solved Threads: 156
Skill Endorsements: 10
JavaPrograms
Junior Poster in Training
72 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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 ...
stephen84s
Nearly a Posting Virtuoso
1,444 posts since Jul 2007
Reputation Points: 668
Solved Threads: 156
Skill Endorsements: 10
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.
JamesCherrill
... trying to help
8,525 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30
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);
JavaPrograms
Junior Poster in Training
72 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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.
JamesCherrill
... trying to help
8,525 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30
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?
JavaPrograms
Junior Poster in Training
72 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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.
JamesCherrill
... trying to help
8,525 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30
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.
JavaPrograms
Junior Poster in Training
72 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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.
JamesCherrill
... trying to help
8,525 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30
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!
JavaPrograms
Junior Poster in Training
72 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 1 Year Ago by
David Kroukamp,
JamesCherrill
and
stephen84s