Java File Read in As Array - java

I am really stuck here, I can't seem to read in the arrays properly.
I can't seem to read in these arrays into columns. Looking for a solution to help me finally make an array out of these numbers.
public class TextFileInputAndOutput
{
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("USStateCapitalsSelected.txt"));
int lineCounter = 1;
String line;
while ((line = reader.readLine()) != null) {
// parse line using any method.
// example 1:
Scanner intScanner = new Scanner(line);
while (intScanner.hasNextLine()) {
String nextInt = intScanner.nextLine();
System.out.println(nextInt + "Herro");
if (intScanner.hasNextDouble() == true) {
Scanner scanner = new Scanner(line);
while (scanner.hasNextDouble()) {
String nextString = scanner.next();
System.out.println(nextString);
}
}
}
}
}
}

You can use com.google.common.io.Files:
Sample.txt:
nameA labA quizeA
nameB labB quizeB
Code:
public static void main(String[] args) throws Exception {
File myFile = new File("Sample.txt");
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> labs = new ArrayList<String>();
ArrayList<String> quizes = new ArrayList<String>();
for (String line : Files.readLines(myFile, Charset.defaultCharset())) {
String[] cols = line.split(" ");
names.add(cols[0]);
labs.add(cols[1]);
quizes.add(cols[2]);
}
System.out.println(names);
System.out.println(labs);
System.out.println(quizes);
}

Tryb this
try{
File file = new File("filename");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] temp = line.split(" ");
//add values to arraylist
names.add(temp[0]);
labs.add(temp[1]);
quizes.add(temp[2]);
}
}catch (Exception ex) {
ex.printStackTrace();
}

Related

How to sort a cvs file by one field in Java?

How can I sort a cvs file by one field in Java?
For example I want to sort it by the third field
I have a cvs file that looks like this:
1951,Jones,5
1984,Smith,7
...
I tried using Scanner as such, with a delimiter but I couldn't figure out how to go on:
public static void main(String[] args)
{
//String data = args[0];
Scanner s = null;
String delim = ";";
try
{
s = new Scanner(new BufferedReader (new FileReader("test.csv")));
List<Integer> three = new ArrayList<Integer>();
while(s.hasNext())
{
System.out.println(s.next());
s.useDelimiter(delim);
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
finally
{
if(s != null)
{
s.close();
}
}
}
Thank you!
public static void main(String[] args)
{
final String DELIM = ";";
final int COLUMN_TO_SORT = 2; //First column = 0; Third column = 2.
List<List<String>> records = new ArrayList<>();
try (Scanner scanner = new Scanner(new File("test.csv"))) {
while (scanner.hasNextLine()) {
records.add(getRecordFromLine(scanner.nextLine(), DELIM));
}
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
Collections.sort(records, new Comparator<List<String>>(){
#Override
public int compare(List<String> row1, List<String> row2){
if(row1.size() > COLUMN_TO_SORT && row2.size() > COLUMN_TO_SORT)
return row1.get(COLUMN_TO_SORT).compareTo(row2.get(COLUMN_TO_SORT));
return 0;
}
});
for (Iterator<List<String>> iterator = records.iterator(); iterator.hasNext(); ) {
System.out.println(iterator.next());
}
}
private static List<String> getRecordFromLine(String row, String delimiter) {
List<String> values = new ArrayList<String>();
try (Scanner rowScanner = new Scanner(row)) {
rowScanner.useDelimiter(delimiter);
while (rowScanner.hasNext()) {
values.add(rowScanner.next());
}
}
return values;
}
** Note that the example file is separated by comma, but in the code you use semicolon as the delimiter.

How do I store the CSV file data into an array in Java?

Here is the CSV file I am using:
B00123,55
B00783,35
B00898,67
I need to read and store the first value entered in the file e.g. B00123 and store it into an array. A user can add to the file so it is not a fixed number of records.
So far, I have tried this code:
public class ArrayReader
{
static String xStrPath;
static double[][] myArray;
static void setUpMyCSVArray()
{
myArray = new double [4][5];
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "src\\marks.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] InArray = InputLine.split(",");
//copy the content of the inArray to the myArray
for (int x = 0; x < myArray.length; x++)
{
myArray[Rowc][x] = Double.parseDouble(InArray[x]);
}
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (int Rowc = 0; Rowc < 1; Rowc++)
{
for (int Colc = 0; Colc < 5; Colc++)
{
System.out.println(myArray[Rowc][Colc] + " ");
}
System.out.println();
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
This loops round the file but doesn't not populate the array with any data. The outcome is:
****** Setup Array ******
[[D#42a57993
0.0
0.0
0.0
0.0
0.0
There is actually a NumberFormatException happening when in the first row when trying to convert the ID to Double. So I revised the program and it works for me.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ArrayReader
{
static String xStrPath;
static Map<String,Double> myArray = new HashMap<>();
static void setUpMyCSVArray()
{
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "/Users/admin/Downloads/mark.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] inArray = InputLine.split(",");
//copy the content of the inArray to the myArray
myArray.put(inArray[0], Double.valueOf(inArray[1]));
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
System.out.println(e);
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (String key : myArray.keySet()) {
System.out.println(key + " = " + myArray.get(key));
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
Output:
the code can't reader anything ,you file path incorrect.give it absoulte file path.
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
I use opencsv library to read from csv.
import com.opencsv.CSVReader;
public class CSV {
private static String file = <filepath>;
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] line;
while ((line = reader.readNext()) != null) {
list.add(line[0]);
}
Object[] myArray = list.toArray();
System.out.println(myArray.length);
System.out.println(myArray[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output printed as below
3
B00123

Converting lines of text from a file to String Array

I read the information in a .txt file and now I would like to store the lines of information from the text into a String Array or a variable.
The information in the .txt file is as given:
Onesimus, Andrea
BAYV
Twendi, Meghan
RHHS
Threesten, Heidi
MDHS
I want to store BAYV, RHHS, MDHS into a different array from the names.
import java.io.File;
import java.util.Scanner;
class testing2 {
public static void main(String [] args) throws Exception {
File Bayviewcamp = new File ("H:\\Profile\\Desktop\\ICS3U\\Bayviewland Camp\\Studentinfo.txt");
Scanner scanner = new Scanner (Bayviewcamp);
while (scanner.hasNextLine())
System.out.println(scanner.nextLine());
Check whether names matches with the regex "[A-Z]+"
List<String> upperCaseList = new ArrayList<>();
List<String> lowerCaseList = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] names = scanner.nextLine().split(",");
for(String name:names) {
if(name.matches("[A-Z]+")) {
upperCaseList.add(name);
}
else {
lowerCaseList.add(name);
}
}
}
As per your example, some of the names has leading spaces. you may have to trim those spaces before you compare with the regex
for(String name:names) {
if(name.trim().matches("[A-Z]+")) {
upperCaseList.add(name.trim());
}
else {
lowerCaseList.add(name.trim());
}
}
Below code has few restrictions like:
There must be format that you said (name and next line value)
Array size is 100 by default but you can change as you want
By name I mean one line: (Onesimus, Andrea) it's under first index in names array.
private static final int ARRAY_LENGTH = 100;
public static void main(String[] args) throws FileNotFoundException {
boolean isValue = false;
File txt = new File("file.txt");
Scanner scanner = new Scanner(txt);
String[] names = new String[ARRAY_LENGTH];
String[] values = new String[ARRAY_LENGTH];
int lineNumber = 0;
while (scanner.hasNextLine()) {
if (isValue) {
values[lineNumber / 2] = scanner.nextLine();
} else {
names[lineNumber / 2] = scanner.nextLine();
}
isValue = !isValue;
lineNumber++;
}
for (int i = 0; i < ARRAY_LENGTH; i++) {
System.out.println(names[i]);
System.out.println(values[i]);
}
}
Below code return separated names:
private static final int ARRAY_LENGTH = 100;
public static void main(String[] args) throws FileNotFoundException {
boolean isValue = false;
File txt = new File("file.txt");
Scanner scanner = new Scanner(txt);
String[] names = new String[ARRAY_LENGTH];
String[] values = new String[ARRAY_LENGTH];
int namesNumber = 0;
int valuesNumber = 0;
while (scanner.hasNextLine()) {
if (!isValue) {
String tempArrayNames[] = scanner.nextLine().split(",");
values[valuesNumber++] = tempArrayNames[0].trim();
values[valuesNumber++] = tempArrayNames[1].trim();
} else {
names[namesNumber++] = scanner.nextLine();
}
isValue = !isValue;
}
}

Reached end of file while parsing error

I created this code in Java but I am getting the following error:
"Reached end of file while parsing error".
Can someone please have a look at it?
import java.io.*;
import java.util.Scanner;
public class ParseTest {
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;
}
I have checked the curly braces error but nothing helps.
You are missing a curly brace. This is what your code should look like:
import java.io.*;
import java.util.Scanner;
public class ParseTest
{
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;
}
}
Line up your brackets, makes it much easier to read.

Reading in information into separate arrays

I've been having some difficulties reading in information from a file into separate arrays. An example of the information in the file is:
14 Barack Obama:United States
17 David Cameron:United Kingdom
27 Vladimir Putin:Russian Federation
19 Angela Merkel:Germany
While I can separate the integers into an array, I am having trouble creating an array for the names and an array for the countries. This is my code thus far:
import java.util.*;
import java.io.*;
public class leadRank {
public static void main(String[] args) throws FileNotFoundException {
int size;
Scanner input = new Scanner(new File("names.txt"));
size = input.nextInt();
int[] rank = new int[size];
for (int i = 0; i < rank.length; i++) {
rank[i] = input.nextInt();
input.nextLine();
}
String[] name = new String[size];
for (int i = 0; i <name.length; i++) {
artist[i] =
I think that I would have to read in the line as a string and use indexOf to find the colon in order to start a new array but I'm unsure as to how to execute that.
I just tried to solve your problem in my ways. It was just for a time pass. Hopes this may helps you.
import java.util.*;
import java.io.*;
public class leadRank {
public static void main(String[] args) throws FileNotFoundException {
int size;
File file = new File("names.txt");
FileReader fr = new FileReader(file);
String s;
LineNumberReader lnr = new LineNumberReader(new FileReader(file));
lnr.skip(Long.MAX_VALUE);
size = lnr.getLineNumber()+1;
lnr.close();
int[] rank = new int[size];
String[] name = new String[size];
String[] country = new String[size];
try {
BufferedReader br = new BufferedReader(fr);
int i=0;
while ((s = br.readLine()) != null) {
String temp = s;
if(temp.contains(":")){
String[] splitres = temp.split(":");
String sub = splitres[0];
rank[i] = Integer.parseInt(sub.substring(0,sub.indexOf(" "))); // Adding rank to array rank[]
name[i] = sub.substring(sub.indexOf(" "), sub.length()-1); // Adding name to array name[]
country[i] = splitres[1]; // Adding the conutries to array country[]
}
i++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This is a bit more efficient because it goes through the file only once.
public static void main(String[] args) throws FileNotFoundException {
// create an array list because the size of the array is still not know
ArrayList<Integer> ranks = new ArrayList<Integer>();
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> countries = new ArrayList<String>();
// read the input file
Scanner input = new Scanner(new File("names.txt"));
// read each line
while (input.hasNext()) {
String wholeLine = input.nextLine();
// get the index of the first space
int spaceIndex = wholeLine.indexOf(" ");
// parse the rank
int rank;
try {
rank = Integer.parseInt(wholeLine.substring(0, spaceIndex));
} catch (NumberFormatException e) {
rank = -1;
}
// parse the name & country
String[] tokens = wholeLine.substring(spaceIndex + 1).split(":");
String name = tokens[0];
String country = tokens[1];
// add to the arrays
ranks.add(rank);
names.add(name);
countries.add(country);
}
// get your name and country arrays if needed
String[] nameArr = names.toArray(new String[]{});
String[] countryArr = countries.toArray(new String[]{});
// the rank array has to be created manually
int[] rankArr = new int[ranks.size()];
for (int i = 0; i < ranks.size(); i++) {
rankArr[i] = ranks.get(i).intValue();
}
}

Categories

Resources