Java Reading a File into an Arraylist

Java reading a file into an ArrayList?

This Java code reads in each word and puts it into the ArrayList:

Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
s.close();

Use s.hasNextLine() and s.nextLine() if you want to read in line by line instead of word by word.

Reading text file into arraylist

Read from a file and add each line into arrayList. See the code for example.

public static void main(String[] args) {

ArrayList<String> arr = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(<your_file_path>)))
{

String sCurrentLine;

while ((sCurrentLine = br.readLine()) != null) {
arr.add(sCurrentLine);
}

} catch (IOException e) {
e.printStackTrace();
}

}

How to read file into an Arraylist and print the ArrayList in Java

The Correct Syntax for Scanner :
Scanner s = new Scanner(new File("A.txt") );

Object

In java Object is the superclass of all the classes ie. predefined sucs as String or any user defined .

It will accepts any kind of data such as string or any other types contained in the A.txt file.

========================================================================

import java.io.*;
import java.util.*;
class B{
public static void main(String aregs[]) throws FileNotFoundException {
Scanner s = new Scanner(new File("A.txt") );

ArrayList<Object> list = new ArrayList<Object>();
while(s.hasNext()) {
list.add(s.next());
}
System.out.println(list);

}
}

How to read from a file into an array List of a specific object

When reading in lines of text from a data file using Scanner, don't use the Scanner#next() method unless you specifically want each token (word) from the file. It's specifically designed for retrieving tokens (words) from a file when used with the Scanner#hasNext() method. Use Scanner#hasNextLine() in conjunction with the Scanner#nextLine() method instead. Here is an example:

File customerFile = new File("Accounts.txt");
ArrayList<String> accountsList = new ArrayList<>();
// Try With Resources...
try (Scanner input = new Scanner(customerFile)) {
while (input.hasNextLine()) {
String line = input.nextLine().trim(); // Trim each line as they are read.
if (line.equals("")) { continue; } // Make sure a data line is not blank.
accountsList.add(line); // Add the data line to Account List
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}

You will notice that I don't name the Account List as list2. Although it's a matter of preference it's simply not descriptive enough. I conveniently named it accountsList which makes it much easier to see what the variable is for.

Although you can get away with it, I wouldn't use the contains() method for checking User Name and Password. It's not accurate enough as you will find when the Account List would get larger. Instead, split each account line into a String Array and access the specific indexes where the User Names and Passwords would reside, for example:

int accountIndex = -1;
for (int i = 0; i < accountsList.size(); i++) {
// Split the current accounts data line into a String Array
String[] userData = accountsList.get(i).split(",");
// Check User Name/Password valitity.
if (userData[1].equals(username) && userData[2].equals(password)) {
accountIndex = i;
break; // Success - We found it. Stop Looking.
}
}

Now, this of course is under the assumption that in each Account data line the first item is a ID Number, the second item is the User Name and the thirst item is the Password. If this line was split into a String array that would then make the first item (ID) reside at Array Index 0, the second item (User Name) reside at Array Index 1, and the third item (Password) reside at Array Index 2, and so on.

You also have a variable named accountIndex (good name) but upon a successful find of the User Name and Password you supply 0 to this variable. By doing this you are effectively telling your code that the successful account is actually the very first account contained within the Accounts List regardless of what User Name and Password has passed validity. What you should be passing to this variable is the value contained in i as demonstrated in the example above since this is the true index value of the Accounts List element which passed User Name/Password validity.

The rest of your code has not been supplied therefore you are on your own from here.

Reading a text file & adding the content to an ArrayList

Using Java 7 & Java 8 API's feature, you can solve your problem like below:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LineOperation {

private static List<String> lines;

public static void main(String[] args) throws IOException {

lines = Collections.emptyList();

try {
lines = Files.readAllLines(Paths.get("C:\\Users\\Abhinav\\Downloads\\TempData2018a.txt"), StandardCharsets.UTF_8);

String stationName = lines.get(0);

String[] arr = null;

ArrayList<StationRecord> data = new ArrayList<>();

for(int i=1;i<lines.size();i++) {

arr = lines.get(i).split(" ");

data.add(new StationRecord(Long.parseLong(arr[0]), Integer.parseInt(arr[1]), Integer.parseInt(arr[2]), Integer.parseInt(arr[3]), Double.parseDouble(arr[4])));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

But I strongly recommend you to refer below links for your further clarifications on Java I/O:-

  1. Java – Read from File

  2. Read a File into an ArrayList

How to read from files and store it in ArrayList of objects?

Read the file line by line and use same delimiter you have used in toString of Person class.

Like: let se you have used " " as delimiter.

then read line by line and split the data using that delimiter and convert the data respectively

String line = reader.readLine();
String[] array = line.split(" ")// use same delimiter used to write
if(array.lenght() ==3){ // to check if data has all three parameter
people.add(new Person(array[0], array[1], Double.parseDouble(array[2])));
// you have to handle case if Double.parseDouble(array[2]) throws exception
}

How to read a file containing strings and integers into an ArrayList and sort by integer?

You can create a student object to hold name and grade separately. Once you have added all the data into list you can directly use list.sort() method by using Comparator but in your case you want to write selection sort that's why you have to write another method to do selection sort.

package com.stackovflow.problems;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Grades {

public static void main(String[] args){
ArrayList<Student> list = new ArrayList<>();
String fileName = "students.txt";
try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
while(input.ready()){
String line = input.readLine().trim();
String name = line.substring(0,line.lastIndexOf(' '));
int grade = Integer.parseInt(line.substring(line.lastIndexOf(' ')+1));
list.add(new Student(name, grade));
}
input.close();
selectionSort(list);
System.out.println(list);
} catch (IOException e){
System.out.println(e.getMessage());
}
}

private static void selectionSort(ArrayList<Student> list) {
int pFill;
int pTest;
int pSmallest;
Student temp;
for (pFill = 0; pFill < list.size(); pFill++) {
pSmallest = pFill;
for (pTest = pFill + 1; pTest < list.size(); pTest++) {
Student pTestStudent = list.get(pTest);
Student pSmallestStudent = list.get(pSmallest);
if (pTestStudent.getGrade() < pSmallestStudent.getGrade()) {
pSmallest = pTest;
}
}
if(pSmallest!=pFill) {
temp = list.get(pSmallest);
list.set(pSmallest, list.get(pFill));
list.set(pFill, temp);
}
}

}
}

//This class is to hold line data in your students.txt file
class Student{
private String name;
private int grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public Student(String name, int grade) {
super();
this.name = name;
this.grade = grade;
}
@Override
public String toString() {
return "Student [name=" + name + ", grade=" + grade + "]";
}

}


Related Topics



Leave a reply



Submit