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();
}
Related
I am trying to break down a data text file which is in the format of:
kick, me, 10
kick, you, 20
into arrayList<customlist> = new arrayList
class customlist
{
string something, string something2, int times
}
So my question is how can I get each part of the text file data to each part of the customlist.
eg: kick -> something, me -> something2 and 10 -> times
Try to split each line into its components using String.split(",").
Apply String.trim() to each member in order to get rid of the spaces.
There are many way to solve this type of problem, here you can simply read all text from that text file by using InputStream and BufferReader after geting all text you can do somthing like:-
ArrayList<CustomList> getArrayList(String textFileData)
{
ArrayList<CustomList> customLists = new ArrayList<>() ;
String data[] = textFileData.split(",");
int i = data.length;
int position = 0;
while (position<i)
{
String somthing = data[position];
String somthing1 = data[position+1];
String temp = data[position+2].split(" ")[0];
int times = Integer.parseInt(temp);
CustomList customList= new CustomList();
customList.setSomething(somthing);
customList.setSomething2(somthing1);
customList.setTimes(times);
customLists.add(customList);
position = position+3;
}
return customLists;
}
Note: this is refer if you are using same string pattern as you mention in the above problem
Using a Scanner object to read the lines and breaking up each line using the split() function. Then, create a new customlist object, and add it into your ArrayList<customlist>.
public void readFile(File file, ArrayList<customlist> myList)
{
Scanner sc = new Scanner(file);
String line;
while(sc.hasNextLine())
{
line=sc.nextLine();
String[] fields = line.split(",");
int times = Integer.parseInt(fields[2].trim());
customlist myCustom = new myList(fields[0].trim(), fields[1].trim(),
times);
myList.add(myCustom);
}
sc.close();
}
You may also handle exceptions if you think its necessary.
How do I read from a txt file with lines of unknown size? For example:
Family1,john,mark,ken,liam
Family2,jo,niamh,liam,adam,apple,joe
Each line has a different number of names. I am able to read in when using object type like
family(parts[0], parts[1], parts[2])
but thats if I know the amout that will be in each. how do I read it in without knowing how many will be in each?
FileReader fr = new FileReader("fam.txt");
BufferedReader br = new BufferedReader(fr);
String fileLines;
String[] parts;
while(br.ready())
{
fileLines = br.readLine();
parts = fileLines.split(",");
.
.
You can use varargs for your family() method to accept the array: family(String ... parts) or just use family(String[] parts).
Personally, I would create a separate class Family and not pollute it with implementation detail about the file format (i.e. that the first item on each line is the family name):
public class Family {
private final List<String> members = new ArrayList<>();
private final String familyName;
public Family(String familyName, Collection<String> members) {
this.familyName = familyName;
this.members.addAll(members);
}
}
Then your loop can be like this:
List<Family> families = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
List<String> parts = Arrays.asList(line.split(","));
String familyName = parts.remove(0);
families.add(new Family(familyName, parts));
}
ArrayList<E>: Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null, provides methods to manipulate the size of the array that is used internally to store the list.
Each ArrayList instance has a capacity: size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
So just read your data and add to the array-list using ArrrayList.add(E e) method.
You're struggling since you try to load the data to an String[] which is in turn a plain array. You should use ArrayList that maintains an internal array and it increase its size dynamically.
FileReader fr = new FileReader("fam.txt");
BufferedReader br = new BufferedReader(fr);
String fileLines;
String[] parts;
List<List<String>> data = new ArrayList<>();
while(br.ready()) {
fileLines = br.readLine();
parts = fileLines.split(",");
data.add(Arrays.asList(parts));
//do what you want/need...
}
//do what you want/need...
A better approach would be parsing the data in String[] parts and build an object of some class that will contain the data for your specific case:
public void yourMethod() {
FileReader fr = new FileReader("fam.txt");
BufferedReader br = new BufferedReader(fr);
String fileLines;
String[] parts;
List<Family> familyList = new ArrayList<>();
while(br.ready()) {
fileLines = br.readLine();
parts = fileLines.split(",");
Family family = new Family(parts[0], parts[1], parts[2]);
familyList.add(family);
//do what you want/need...
}
//do what you want/need...
}
My personal preference is to use the Scanner class. You can review the functionality here. With the scanner you can parse the file a line at a time and store those values into a String.
Scanner scan = new Scanner(new File("fam.txt"));
List<String> families = new ArrayList<String>();
while(scan.hasNextLine()){
families.add(scan.nextLine());
}
Then you can do whatever you want with the families in the ArrayList
use a Scanner, that's much easier. You can put both in a while loop
Scanner sc = new Scanner(new File(myFile.txt));
while(sc.hasNextLine()) {
while(sc.hasNextString()) {
String str = sc.nextString();
}
}
This is a simplefied version and it will not work correctly, because you have to store some values in variables for Java to read them correctly. Read the documentation on the Java Scanner to find a more detailed explanation. The Scanner is much easier than what you have been doing
I'm having trouble scanning a given file for certain words and assigning them to variables, so far I've chosen to use Scanner over BufferedReader because It's more familiar. I'm given a text file and this particular part I'm trying to read the first two words of each line (potentially unlimited lines) and maybe add them to an array of sorts. This is what I have:
File file = new File("example.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] ary = line.split(",");
I know It' a fair distance off, however I'm new to coding and cannot get past this wall...
An example input would be...
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
...
and the proposed output
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
...
You can try something like this
File file = new File("D:\\test.txt");
Scanner sc = new Scanner(file);
List<String> list =new ArrayList<>();
int i=0;
while (sc.hasNextLine()) {
list.add(sc.nextLine().split(",",2)[0]);
i++;
}
char point='A';
for(String str:list){
System.out.println("Variable"+point+" = "+str);
point++;
}
My input:
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
Out put:
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
To rephrase, you are looking to read the first 2 words of a line (everything before the first comma) and store it in a variable to process further.
To do so, your current code looks fine, however, when you grab the line's data, use the substring function in conjunction with indexOf to just get the first part of the String before the comma. After that, you can do whatever processing you want to do with it.
In your current code, ary[0] should give you the first 2 words.
public static void main(String[] args)
{
File file = new File("example.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
List l = new ArrayList();
while ((line = br.readLine()) != null) {
System.out.println(line);
line = line.trim(); // remove unwanted characters at the end of line
String[] arr = line.split(",");
String[] ary = arr[0].split(" ");
String firstTwoWords[] = new String[2];
firstTwoWords[0] = ary[0];
firstTwoWords[1] = ary[1];
l.add(firstTwoWords);
}
Iterator it = l.iterator();
while (it.hasNext()) {
String firstTwoWords[] = (String[]) it.next();
System.out.println(firstTwoWords[0] + " " + firstTwoWords[1]);
}
}
I'm trying to read in from two files and store them in two separate arraylists. The files consist of words which are either alone on a line or multiple words on a line separated by commas.
I read each file with the following code (not complete):
ArrayList<String> temp = new ArrayList<>();
FileInputStream fis;
fis = new FileInputStream(fileName);
Scanner scan = new Scanner(fis);
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (scan.hasNext()) {
String md5 = scan.next();
temp.add(md5);
}
}
scan.close();
return temp;
Each file contains almost 1 million words (I don't know the exact number), so I'm not entirely sure that the above code works correctly - but it seems to.
I now want to find out how many words are exclusive to the first file/arraylist. To do so I planned on using list1.removeAll(list2) and then checking the size of list1 - but for some reason this is not working. The code:
public static ArrayList differentWords(String fileName1, String fileName2) {
ArrayList<String> file1 = readFile(fileName1);
ArrayList<String> file2 = readFile(fileName2);
file1.removeAll(file2);
return file1;
}
My main method contains a few different calls and everything works fine until I reach the above code, which just causes the program to hang (in netbeans it's just "running").
Any idea why this is happening?
You are not using input in
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (scan.hasNext()) {
String md5 = scan.next();
temp.add(md5);
}
}
I think you meant to do this:
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (input.hasNext()) {
String md5 = input.next();
temp.add(md5);
}
}
but that said you should look into String#split() that will probably save you some time:
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] tokens = line.split(",");
for (String token: tokens) {
temp.add(token);
}
}
try this :
for(String s1 : file1){
for(String s2 : file2){
if(s1.equals(s2)){file1.remove(s1))}
}
}
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