Basic File Reading to Array Storage - java

I have a simple Java questions and I need a simple answer, if possible. I need to input the data from the file and store the data into an array. To do this, I will have to have the program open the data file, count the number of elements in the file, close the file, initialize your array, reopen the file and load the data into the array. I am mainly having trouble getting the file data stored as an array. Here's what I have:
The to read file is here: https://www.dropbox.com/s/0ylb3iloj9af7qz/scores.txt
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.text.*;
public class StandardizedScore8
{
//Accounting for a potential exception and exception subclasses
public static void main(String[] args) throws IOException
{
// TODO a LOT
String filename;
int i=0;
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the file name:");
filename=scan.nextLine();
File file = new File(filename);
//File file = new File ("scores.txt");
Scanner inputFile = new Scanner (file);
String [] fileArray = new String [filename];
//Scanner inFile = new Scanner (new File ("scores.txt"));
//User-input
// System.out.println("Reading from 'scores.txt'");
// System.out.println("\nEnter the file name:");
// filename=scan.nextLine();
//File-naming/retrieving
// File file = new File(filename);
// Scanner inputFile = new Scanner(file);

I recommend you use a Collection. This way, you don't have to know the size of the file beforehand and you'll read it only once, not twice. The Collection will manage its own size.

Yes, you can if you don't care about the trouble of doing things twice. Use while(inputFile.hasNext()) i++;
to count the number of elements and create an array:
String[] scores = new String[i];
If you do care, use a list instead of an array:
List<String> list = new ArrayList<String>();
while(inputFile.hasNext()) list.add(inputFile.next());
You can get list elements like list.get(i), set list element like list.set(i,"string") and get the length of list list.size().
By the way, your line of String [] fileArray = new String [filename];is incorrect. You need to use an int to create an array instead of a String.

/*
* Do it the easy way using a List
*
*/
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the file name:");
String filename = scan.nextLine();
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
List<String> lineList = new ArrayList<String>();
String thisLine = reader.readLine();
while (thisLine != null) {
lineList.add(thisLine);
thisLine = reader.readLine();
}
// test it
int i = 0;
for (String testLine : lineList) {
System.out.println("Line " + i + ": " + testLine);
i++;
}
}

We can use the ArrayList collection to store the values from the file to the array without knowing the size of the array before hand.
You can get more info on ArrayList collections from the following urls.
http://docs.oracle.com/javase/tutorial/collections/implementations/index.html
http://www.java-samples.com/showtutorial.php?tutorialid=234

Related

Object needs to created from the file and placed into an array

I am trying to create an object for each line of text and as each object is created, place it into an array. I'm struggling to place it into an array. This is my code:
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
Shareholder shareholder = new Shareholder();
while (inputFile.hasNext()) {
str = inputFile.nextLine();
String tokens[] = str.split(",");
shareholder.setID(tokens[0]);
shareholder.setName(tokens[1]);
shareholder.setAddress(tokens[2]);
shareholder.setPortfolioID(tokens[3]);
}
If you have a fixed number of shareholders, you can do this -
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
int i=0;
Shareholder[] shareholder = new Shareholder[n];
while (inputFile.hasNext()) {
str = inputFile.nextLine();
String tokens[] = str.split(",");
shareholder[i++] = new Shareholder(tokens[0],tokens[1],tokens[2],tokens[3]);
}
Or if dont know the number of shareholders, then you can use list -
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
List<Shareholder> list = new ArrayList<>();
while (inputFile.hasNext()) {
Shareholder shareholder = new Shareholder();
str = inputFile.nextLine();
String tokens[] = str.split(",");
list.add(new Shareholder(tokens[0],tokens[1],tokens[2],tokens[3]));
}
I think a list of shareholder objects might make the most sense here:
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
List<Shareholder> list = new ArrayList<>();
while (inputFile.hasNext()) {
Shareholder shareholder = new Shareholder();
str = inputFile.nextLine();
String tokens[] = str.split(",");
shareholder.setID(tokens[0]);
shareholder.setName(tokens[1]);
shareholder.setAddress(tokens[2]);
shareholder.setPortfolioID(tokens[3]);
list.add(shareholder);
}
The reason a list makes sense here is because you might not know how many shareholders are present in the input file. Hence, an array might not work so well in this case (and even if the number of shareholders were fixed it could change at some later date).
Before reading the file, you can not know how many lines the file has.
The information about the number of lines is important to initialize your array with that specific size or otherwise you would need to extend your array multiple times by creating a new, bigger one. Which is bad practice and bad performance.
But instead of working with an array itself, use an arraylist for easier usage and just return a simple array, which can be received from the arraylist you worked with.
My suggestion as a solution for this issue is the following. Please note that the following code is not 100% complete and will not run in it's state. It is your job to complete it and make it run.
public void readFileIntoArray(String filename, Shareholder[] targetArray)
{
File sourceFile = new File(filename);
// Read in the file to determine the number of lines (int numberOfLines)
ArrayList<Shareholder> lines = new ArrayList<>(numberOfLines);
Shareholder sh;
while(file.hasNext())
{
sh = new Shareholder();
//Parse data into Shareholderobject
lines.add(sh);
}
return lines.toArray();
}

How to read doubles from .txt file into an ArrayList

I'm trying to read doubles from a file that contains 100,000 doubles, arranged in lines of two doubles each separated by a space. Like this:
2.54343 5.67478
1.23414 5.43245
7.64748 4.25536
...
My code so far:
Scanner numFile = new Scanner(new File("input100K.txt").getAbsolutePath());
ArrayList<Double> list = new ArrayList<Double>();
while (numFile.hasNextLine()) {
String line = numFile.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter(" ");
while(sc.hasNextDouble()) {
list.add(sc.nextDouble());
}
sc.close();
}
numFile.close();
System.out.println(list);
}
After this code runs, it prints to the console and empty ArrayList [], and I can't figure out why.
Removing the getAbsolutePath() from the file gives me this line:
Scanner numFile = new Scanner(new File("input100K.txt"));
but when I run the program, it is giving me a FileNotFoundException. I know the file exists, I can see it and open it.
input100K.txt is located in the src package folder along with the program. is there somewhere specific where the file must be for this to work?
EDIT: As Evgeniy Dorofeev pointed out, the file needs to be in the project folder (parent of src folder) for the program to find it.
When you create Scanner like this new Scanner(new File("input100K.txt").getAbsolutePath()); you are scanning file path as input not file itself. Do it this way new Scanner(new File("input100K.txt"));
You can try using split() method on the line you just have read, then parsing each part to a double. Note that it's not necessary to create two Scanners:
Scanner sc = new Scanner(new File("input100K.txt"));
sc.useDelimiter(" ");
ArrayList<Double> list = new ArrayList<Double>();
while (sc.hasNextLine()) {
String[] parts = sc.nextLine().split(" "); // split each line by " "
for (String s : parts) {
list.add(Double.parseDouble(s)); // parse to double
}
}
sc.close();
System.out.println(list);
replace the line
Scanner numFile = new Scanner(new File("input100K.txt").getAbsolutePath());
with
Scanner numFile = new Scanner(new File("input100K.txt"));
Here is a sample program :
public static void main(String[] args) throws FileNotFoundException {
List<Double> doubleList = new ArrayList<Double>();
Scanner scanner = new Scanner(new File("/home/visruthcv/inputfile.txt"));
while (scanner.hasNextDouble()) {
double value = scanner.nextDouble();
System.out.println(value);
doubleList.add(value);
}
/*
* for test print
*/
for (Double eachValue : doubleList) {
System.out.println(eachValue);
}
}

Counting Postive and Negative words in a file using dictionaries (Java)

I'm trying to determine the number of occurrences positive and negative words in a file to calculate whether the file has a positive or a negative tone.
I'm currently having issues trying to parse a file for the number of positive and negative words contained in the file. At the moment, I'm currently using a BufferedReader to read the main file I'm trying to determine the positive and negative words from as well as the two files containing the dictionary of positive and negative words. However the problem I'm having is its comparing each word with the corresponding word number in the positive and negative files.
Here is my current code:
import java.io.*;
import java.util.Scanner;
public class ParseTest {
public static void main(String args[]) throws IOException
{
File file1 = new File("fileforparsing");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
File file2 = new File("positivewordsdictionary");
BufferedReader br1 = new BufferedReader(new InputStreamReader(new FileInputStream(file2)));
int positive = 0;
Scanner sc1 = new Scanner(br);
Scanner sc2 = new Scanner(br1);
while (sc1.hasNext() && sc2.hasNext()) {
String str1 = sc1.next();
String str2 = sc2.next();
if (str1.equals(str2))
positive = positive +1;
}
while (sc2.hasNext())
System.out.println(positive);
sc1.close();
sc2.close();
}
}
I know whats wrong whereby the scanner is just constantly moving to the next line when I'd like the original file to stay on the same line until it has finished parsing it against the dictionary but I'm not really sure how to make it do what I want. Any help would be greatly appreciated.
Thank you in advance.
This won't work. You would need to reopen the dictionary file every time. The other thing is that it will be awfully slow. If the dictionaries are not too large, you should load them in memory and then do a read only on the file you're trying to analyze.
public static void main(String args[]) throws IOException {
Set<String> positive = loadDictionary("positivewordsdictionary");
Set<String> negative = loadDictionary("negativewordsdictionary");
File file = new File("fileforparsing");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Scanner sc = new Scanner(br);
String word;
long positiveCount = 0;
long negativeCount = 0;
while (sc.hasNext()) {
word = sc.next();
if (positive.contains(word)) {
System.out.println("Found positive "+positiveCount+":"+word);
positiveCount++;
}
if (negative.contains(word)) {
System.out.println("Found negative "+positiveCount+":"+word);
negativeCount++;
}
}
br.close();
}
public static Set<String> loadDictionary(String fileName) throws IOException {
Set<String> words = new HashSet<String>();
File file = new File(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Scanner sc = new Scanner(br);
while (sc.hasNext()) {
words.add(sc.next());
}
br.close();
return words;
}
Update: I've tried running the code and it's working.
Bad approach.. Dont open 2 files simultaneously... First open your positive words file.. Take data out and store it as keys in a Map. Now, do the same for negative words file... Now start reading the file line by line and check if the read String contains positive/negative word.. if yes, increase the count (value of map. initialize values to 0 at the beginning.)
Consider filling a Set (eg. HashSet) with the positive words at the start of your application.
You can use your scanner in a loop to do this:
while(sc2.hasNext()) {
set.add(sc2.next());
}
Then, when you are looping through the other file, you can just check the set to see if it contains the word:
while(sc1.hasNext()) {
if (set.contains(sc1.next()) {
positive++;
}
}

Storing String from file in an ArrayList object?

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Cities {
public static void main(String[] args) throws IOException {
String filename;
System.out.println("Enter the file name : ");
Scanner kb = new Scanner(System.in);
filename = kb.next();
//Check if file exists
File f = new File(filename);
if(f.exists()){
//Read file
File myFile = new File(filename);
Scanner inputFile = new Scanner(myFile);
//Create arraylist object
ArrayList<String> list = new ArrayList<String>();
String cit;
while(inputFile.hasNext()){
cit = inputFile.toString();
list.add(inputFile.toString());
}
System.out.println(list);
}else{
System.out.println("File not found!");
}
}
}
I am trying to read a file and add the contents to an arraylist object (.txt file contains strings), but I am totally lost. Any advice?
You should read the file one line by one line and store it to the list.
Here is the code you should replace your while (inputFile.hasNext()):
Scanner input = null;
try
{
ArrayList<String> list = new ArrayList<String>();
input = new Scanner( new File("") );
while ( input.hasNext() )
list.add( input.nextLine() );
}
finally
{
if ( input != null )
input.close();
}
And you should close the Scanner after reading the file.
If you're using Java 7+, then you can use the Files#readAllLines() to do this task for you, instead of you writing a for or a while loop yourself to read the file line-by-line.
File f = new File(filename); // The file from which input is to be read.
ArrayList<String> list = null; // the list into which the lines are to be read
try {
list = Files.readAllLines(f.toPath(), Charset.defaultCharset());
} catch (IOException e) {
// Error, do something
}
You can do it in one single line with Guava.
final List<String> lines = Files.readLines(new File("path"), Charsets.UTF8);
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#readLines(java.io.File, java.nio.charset.Charset)

Reading two files and then finding the growth rate

I need help trying to read two files that have the census from 2010 and 2000. I have to read both files and then find out the population growth between those two files. I keep getting null for ever single state. I know that I have null for inLine1 and inLine2.
The file looks like this
Alabama,4779736
Alaska,710231
Arizona,6392017
Arkansas,2915918
Code:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class pa10
{
public static void main(String[] args, char[] inLine2, char[] inLine1)
throws java.io.IOException
{
String fileName1 = "Census2000growth.txt";
String fileName2 = "Census2010growth.txt";
int i;
File f = new File("Census2010growth.txt");
if(!f.exists()) {
System.out.println( "file does not exist ");
}
Scanner infile = new Scanner(f);
infile.useDelimiter ("[\t|,|\n|\r]+"); //create a delimiter
final int MAX = 51;
int [] myarray = new int [MAX];
String[] statearray = new String[MAX];
int fillsize;
// set up input stream1
FileReader fr1 = new
FileReader(fileName1);
// buffer the input stream
BufferedReader br1 =
new BufferedReader(fr1);
// set up input stream2
FileReader fr2 = new
FileReader(fileName2);
// buffer the input stream
BufferedReader br2 =
new BufferedReader(fr2);
// read and display1
String buffer1 = "";
ArrayList<String> firstFile1 = new ArrayList<String>();
while ((buffer1 = br1.readLine()) != null) {
firstFile1.add(buffer1);
System.out.println(inLine1); // display the line
}
br1.close();
//Now read the second file or make for this separate method
// read and display2
String buffer2 = "";
ArrayList<String> firstFile2 = new ArrayList<String>();
while ((buffer2 = br2.readLine()) != null) {
firstFile2.add(buffer2);
System.out.println(inLine2); // display the line
}
br2.close();
//Read all the lines in array or list
//After that you can calculate them.
}
}
Read the BufferedReader documentation. Your file isn't formatted with the types of line separators it is expecting. I suggest using a Scanner and setting the line separator to the appropriate pattern, or using String.split
You have two different variables, buffer1 and inline1. Since you never set the value of inline1, it will always be null.

Categories