I am trying to write a program that will perform a calculation from a text file input.
The text file contains the following columns: amount1, amount2, amount3
I have a method named Calculate which takes in these parameters and does the calculation and subsequent actions.
I also have a main method as follows, but am experiencing troubles in getting the tokens into the Calculate mthod parametsrs,
please refer to code below:
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class myProgram
{
public static void main(String[] args) throws IOException {
File file = new File( "data.txt");
Scanner infile = new Scanner(file);
while (infile.hasNext() ){
String str = infile.nextLine();
StringTokenizer st = new StringTokenizer(str, ", ");
// I want to get the output of each of the tokens into the parameters of my Calculate class here
}
infile.close();
}
You are trying to read a csv file so better use a CSVReader rather than implementing of your own. OpenCSV is one of the available choice. Here is sample to read a csv file:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
String amount1 = nextLine[0];
String amount2 = nextLine[1];
String amount3 = nextLine[2];
// yourMethod(amount1,amount2,amount3);
}
Related
I have a basic class FileOutput that will write to a textfile HighScores. I also have a class fileReader that will print out what is written in the textfile. Is there a way to read a line of the textfile HighScores and save it as a String variable? I eventually want to be able to keep track of the top 5 HighScores in a game so I will need a way to compare the latest score to those in the top 5.
Here is my code so far:
import java.util.Scanner;
import java.io.File;
public class FileReader
{
public static void main(String args[]) throws Exception
{
// Read from an already existing text file
File inputFile = new File("./src/HighScores");
Scanner sc = new Scanner(inputFile);
while (sc.hasNext()){
String s = sc.next();
System.out.println(s);
}
}
FileOutput Class:
import java.io.PrintWriter;
import java.io.FileWriter;
import java.util.ArrayList;
public class FileOutput
{
public static void main(String args[]) throws Exception
{
FileWriter outFile = new FileWriter("./src/HighScores");
PrintWriter out = new PrintWriter(outFile);
// Write text to file
out.print("Top Five High Scores");
out.println(50);
out.println(45);
out.println(20);
out.println(10);
out.println(5);
out.close();
}
}
Yes.
I'm not sure if this is the most clever method of doing so, but you could create an ArrayList and create a collection of strings. Instead of out.print'ing you could try this:
ArrayList<String> al = new ArrayList<>();
while (sc.hasNext()){
String s = sc.next();
al.add(s);
}
That will create a list of strings which you could get the top 5 values of later by saying:
String firstPlace = al.get(0);
String secondPlace = al.get(1);
String thirdPlace = al.get(2);
String fourthPlace = al.get(3);
String fifthPlace = al.get(4);
I write the like reading tsv file with
datarow.splite("\t");
but if the tsv file contain "\t" it displaying \t means it is taking \t as normal text
public class Tsv_read{
public static void main(String[] arg) throws Exception {
BufferedReader TSVFile =
new BufferedReader(new FileReader("users.tsv"));
String dataRow = TSVFile.readLine(); // Read first line.
while (dataRow != null){
String[] dataArray = dataRow.split("\t");
for (String item:dataArray) {
System.out.print(item + " ");
}
System.out.println(); // Print the data line.
dataRow = TSVFile.readLine(); // Read next line of data.
}
// Close the file once all data has been read.
TSVFile.close();
// End the printout with a blank line.
System.out.println();
} //main()
} // TSVRead
Don't try to parse TSV by hand as there are a few corner cases such as escaping/unescaping, not to mention performance/memory issues with large files & lack of flexibility (especially converting values, choosing what columns to read and in what order, etc).
Try uniVocity-parser's TSV parser. Here's a simple example:
TsvParserSettings settings = new TsvParserSettings(); //you will find MANY options here
TsvParser parser = new TsvParser(settings);
// parses all rows in one go.
List<String[]> allRows = parser.parseAll(YOUR_INPUT_HERE);
Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).
Try this code I hope that helps you
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Tsv_read{
public static void main(String[] arg) throws Exception {
StringTokenizer st ;
BufferedReader TSVFile = new BufferedReader(new FileReader("users.tsv"));
String dataRow = TSVFile.readLine(); // Read first line.
while (dataRow != null){
st = new StringTokenizer(dataRow,"\t");
List<String>dataArray = new ArrayList<String>() ;
while(st.hasMoreElements()){
dataArray.add(st.nextElement().toString());
}
for (String item:dataArray) {
System.out.print(item + " ");
}
System.out.println(); // Print the data line.
dataRow = TSVFile.readLine(); // Read next line of data.
}
// Close the file once all data has been read.
TSVFile.close();
// End the printout with a blank line.
System.out.println();
} //main()
} // TSVRead
it is working with stringtokenizer
while (dataRow != null){
st = new StringTokenizer(dataRow,"\\t");
while(st.hasMoreElements()){
dataArray.add(st.nextElement().toString());
}
I am creating a program that will produces the statistics of a baseball team
i am trying to create a constructor to read the file into the teamName instance variable and the battingAverages array.
the txt file contains the one word name of the team followed by 20 batting averages.
"Tars 0.592 0.427 0.194 0.445 0.127 0.483 0.352 0.190 0.335 0.207 0.116 0.387 0.243 0.225 0.401 0.382 0.556 0.319 0.475 0.279 "
I am struggling to find how to go about this and get it started?
I ran this and this might be close to what you want. Instead of making a confusing constructor, make a private method that the constructor will call to read in the file into the array.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Baseball {
private File textFile;
private Scanner input;
private String teamName;
//this will only work if you know there will be 20 entries everytime
//otherwise I recommend loading the data into an ArrayList
private double []battingAvgs = new double[20];
public Baseball(String file){
textFile = new File(file);
readInFile(textFile);
}
//private method that reads in the file into an array
private void readInFile(File textFile){
try {
input = new Scanner(textFile);
//read first string into variable teamName
teamName = input.next();
int i=0;
//iterate through rest of file adding it to an ArrayList
while(input.hasNext()){
battingAvgs[i] = input.nextDouble();
i++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//print out array
public void printArray(){
for(Double a: battingAvgs){
System.out.println(a);
}
}
}
Well, if these are all on one line in a specific file then what you could do is construct a bufferedreader to read the first line of your file, split the line based on spaces, and then parse the teamName and batting averages out.
BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
String[] line = br.readLine().split(" ");
br.close();
teamName = line[0];
battingAverages = new int[20];
for(int i = 0; i < 20; i++)
battingAverages[i] = Integer.parseInt(line[i+1]);
These might throw IOExceptions, which you will need to catch. I think Java 7 has a method to automatically handle these kinds of errors (not sure about this), but as I am new to Java 7's added functionality, I would just manually check for those exceptions.
You need to use the BufferedReader, FileInputStream, and InputStreamReader. Your file.txt should have the batting averages on every line, as shown below.
0.592
0.427
0.194
Here is an example of a class that when created, it will read a text file line by line and add each line to the array list:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Class {
ArrayList<Double> averages;
public Class() {
averages = new ArrayList<Double>();
try {
FileInputStream in = new FileInputStream("inputFile.txt"); //your file path/name
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine = br.readLine())!= null) averages.add(Double.parseDouble(strLine));
}catch(Exception e){
System.out.println(e);
}
}
}
Hope this helps
Try using the Scanner class.
File file=new File("TestFile.txt"); //Create a new file
Scanner scan=new Scanner(file);//Create a Scanner object (Throws FileNotFoundException)
if(scan.hasNext()) //Check to make sure that there is actually something in the file.
{
String line=scan.nextLine(); //Read the line of data
String[] array=line.split(" "); //Split line into the different parts
teamName=array[0]; //The team name is located in the first index of the array
battingAverages=new double[array.length-1];//Create a new array to hold the batting average values
for(int i=0;i<battingAverages.length;i++) //Loop through all of the averages
{
double average=Double.parseDouble(array[i+1]);//Convert the string object into a double
battingAverages[i]=average; //Add the converted average to the array
}
System.out.print(teamName+" "+Arrays.toString(battingAverages)); //[Optional] Print out the resulting values
}
I'm pretty new to Java still and I'm working on a project for class, and I'm unsure of how I write my program to take the userInput(fileName) and create a new object from that. My instructions are to write a program which reads in a file name from the user and then reads the data from that file, creates objects(type StudentInvoice) and stores them in an ArrayList.
This is where I am right now.
public class StudentInvoiceListApp {
public static void main (String[] args) {
Scanner userInput = new Scanner(System.in);
String fileName;
System.out.println("Enter file name: ");
fileName = userInput.nextLine();
ArrayList<StudentInvoice> invoiceList = new ArrayList<StudentInvoice>();
invoiceList.add(new StudentInvoice());
System.out.print(invoiceList + "\n");
}
You may try to write a class for serializing / deserializing objects from a stream (see this article).
Well, as Robert said, there's not enough information about the format of the data stored in the file. Suppose each line of the file contains all the information for a student. Your program will consist of reading a file by lines and create a StudentInvoice for each line. Something like this:
public static void main(String args[]) throws Exception {
Scanner userInput = new Scanner(System.in);
List<StudentInvoice> studentInvoices = new ArrayList<StudentInvoice>();
String line, filename;
do {
System.out.println("Enter data file: ");
filename = userInput.nextLine();
} while (filename == null);
BufferedReader br = new BufferedReader(new FileReader(filename));
while ( (line = br.readLine()) != null) {
studentInvoices.add(new StudentInvoice(line));
}
System.out.println("Total student invoices: " + studentInvoices.size());
}
I have a following test file :
Jon Smith 1980-01-01
Matt Walker 1990-05-12
What is the best way to parse through each line of this file, creating object with (name, surname, birthdate) ? Of course this is just a sample, the real file has many records.
import java.io.*;
class Record
{
String first;
String last;
String date;
public Record(String first, String last, String date){
this.first = first;
this.last = last;
this.date = date;
}
public static void main(String args[]){
try{
FileInputStream fstream = new FileInputStream("textfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] tokens = strLine.split(" ");
Record record = new Record(tokens[0],tokens[1],tokens[2]);//process record , etc
}
in.close();
} catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFile {
public static void main(String[] args) {
//
// Create an instance of File for data.txt file.
//
File file = new File("tsetfile.txt");
try {
//
// Create a new Scanner object which will read the data from the
// file passed in. To check if there are more line to read from it
// we check by calling the scanner.hasNextLine() method. We then
// read line one by one till all line is read.
//
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
This:
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Could also be changed to
while (scanner.hasNext()) {
String line = scanner.next();
Which will read whitespace.
You could do
Scanner scanner = new Scanner(file).useDelimiter(",");
To do a custom delimiter
At the time of the post, now you have three different ways to do this. Here you just need to parse the data you need. You could read the the line, then split or read one by one and everything 3 would a new line or a new person.
At first glance, I would suggest the StringTokenizer would be your friend here, but having some experience doing this for real, in business applications, what you probably cannot guarantee is that the Surname is a single name (i.e. someone with a double barrelled surname, not hyphenated would cause you problems.
If you can guarantee the integrity of the data then, you code would be
BufferedReader read = new BufferedReader(new FileReader("yourfile.txt"));
String line = null;
while( (line = read.readLine()) != null) {
StringTokenizer tokens = new StringTokenizer(line);
String firstname = tokens.nextToken();
...etc etc
}
If you cannot guarantee the integrity of your data, then you would need to find the first space, and choose all characters before that as the last name, find the last space and all characters after that as the DOB, and everything inbetween is the surname.
Use a FileReader for reading characters from a file, use a BufferedReader for buffering these characters so you can read them as lines. Then you have a choice.. Personally I'd use String.split() to split on the whitespace giving you a nice String Array, you could also tokenize this string.
Of course you'd have to think about what would happen if someone has a middle name and such.
Look at BufferedReader class. It has readLine method. Then you may want to split each line with space separators to construct get each individual field.