Reading in file into a string array - java

How do I read in a file into a string array using Scanner? The file has a specified number of lines, lets say 100. There are plenty of examples in here using arrayList and BufferedReader but not Scanner or arrays that are already fixed in size.
public String[] array;
Scanner inputStream = null;
public String line;
public practice(String theFile) {
array = new String[100];
try {
inputStream = new Scanner(new FileInputStream(theFile));
while (inputStream.hasNextLine()) {
for (int i = 0; i < array.length; i++){
//dont know what to put here
}
}
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
inputStream.close();
}

You don't need to check for has next line because you have a fixed length and a try catch to handle it all. Just use the for loop but not the while loop. From there, it's just all scanner stuff:
for (int i = 0; i < array.length; i++)
{
array[i] = inputStream.nextLine();
}

int i = 0;
while (inputStream.hasNextLine() && i < array.length())
{
array[i] = inputStream.nextLine();
i++;
}

Related

reading and writing files java

I have a float array which I stored in it some values from user input.
I have 2 methods one that saves the values stored in the array to a text file each value on a line and the second method rereads the values again and stores them in the array. for example, the user input was 1,2,3,4 I save them to a text file and then I read the same txt file now my array should display 8 elements 1,2,3,4,1,2,3,4.
the problem I'm having is that when I store these elements on the txt file it's storing them and adding like 100 zeros under them and when I'm calling the second method to reread these elements from the file it reads the zeros so when I'm displaying the elements in my array it's displaying 0,0,0,0 when it should display 1,2,3,4,1,2,3,4.
what might be causing me this problem?
public void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file dont exist");
e.printStackTrace();
}
}
public void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
You may check why the array is populated properly using additional println statement. In your version each element of array is populated with the same element read from the file. If you remove the inner loop, array will be populated properly.
int i=0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
System.out.println((i) + "::"+numbers[i]);
i++;
}
Zeros are being added because you're saving numbers as float. If you store an integer 3 in a float variable it will be converted to a float equivalent which is 3.0
Also you don't need two loops here,
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
You can instead do following,
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
Following is a fully functional program of what you desire,
import java.util.Scanner;
import java.io.*;
public class Hello {
public static float[] numbers = {1,2,3,4,1,2,3,4};
public static void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file doesn't exist");
e.printStackTrace();
}
}
public static void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
for(int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
saveValuesToFile(scanner);
readFromFile(scanner);
}
}

How to get data from a CSV file and place it in a list

I want to read data from a CSV file in Java and then put this data into a list. The data in the CSV is put into rows which looks like:
Data, 32, 4.3
Month, May2, May 5
The code I have currently only prints the [32].
ArrayList<String> myList = new ArrayList<String>();
Scanner scanner = new Scanner(new File("\\C:\\Users\\Book1.csv\\"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
myList.add(scanner.next());
for (int i = 0; i <= myList.size(); i++) {
System.out.println(myList.toString());
}
scanner.close();
}
Maybe this code can help you, maybe this code is different from yours, you use arrayList while I use regular array.
Example of the data:
Farhan,3.84,4,72
Rajab,2.98,4,72
Agil,2.72,4,72
Alpin,3.11,4,73
Mono,3,6,118 K
imel,3.97,7,132
Rano,2.12,6,110
Kukuh,4,1,22
Placing data on each row in a csv file separated by commas into the array of each index
int tmp = 0;
String read;
Mahasiswa[] mhs = new Mahasiswa[100];
BufferedWriter outs;
BufferedReader ins;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
try {
ins = new BufferedReader(new FileReader("src/file.csv"));
tmp = 0;
while ((read = ins.readLine()) != null) {
String[] siswa = read.split(",");
mhs[tmp] = new Mahasiswa();
mhs[tmp].nama = siswa[0];
mhs[tmp].ipk = Float.parseFloat(siswa[1]);
mhs[tmp].sem = Integer.parseInt(siswa[2]);
mhs[tmp].sks = Integer.parseInt(siswa[3]);
tmp++;
i++;
}
ins.close();
} catch (IOException e) {
System.out.println("Terdapat Masalah: " + e);
}
Print the array data
tmp = 0;
while (tmp < i) {
System.out.println(mhs[tmp].nama + "\t\t" +
mhs[tmp].ipk + "\t\t" +
mhs[tmp].sem + "\t\t" +
mhs[tmp].sks);
tmp++;
}
ArrayList<String> myList = new ArrayList<String>();
try (Scanner scanner = new Scanner(new File("C:\\Users\\Book1.csv"))) {
//here at your code there are backslashes at front and end of the path that was the
//main reason you are not able to read csv file
scanner.useDelimiter(",");
while (scanner.hasNext()) {
myList.add(scanner.next());
}
for (int i = 0; i < myList.size(); i++) { //remember index is always equal to "length - 1"
System.out.println(myList);
}
} catch (Exception e) {
e.printStackTrace();
}
you also did not handle the FileNotFoundException
Hope this helps:)

Reading a text file into a char[][] array in Java

I am trying to fill a char[][] array from a text file and I cannot seem to figure out how to do it. I've tried to use .toCharArray() but it doesn't seem to work. If you can give any insight on how to make this work that would be awesome!
String filename = "ArrayHW2.txt";
int numTests = 6;
char[][] testAnswers = new char[50][5];
char[] key = new char[4];
Scanner input = null;
try
{
input = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening File");
System.exit(1);
}
for(int row = 0; row < testAnswers.length; row++)
{
for(int col = 0; col < testAnswers[row].length; col++)
{
testAnswers[row][col] = input.next().toCharArray();
}
}
input.close();
The basic problem is that you are trying to assign a character array to something was meant to hold a character. You might think of char[] type as storing the location in memory where characters are recorded, and a char type as the character itself.
When you call toCharArray() on a String, the return type is char[]. It looks like you expect this array to have a single character, like the A, B, C, or D of a multiple-choice test. You could get the first (and only?) character of that array with something like ...toCharArray()[0], but this is wasteful because a new array is created, and characters are copied into it from the source string. It's simpler to use the getCharAt() method on the String directly.
String filename = "ArrayHW2.txt";
char[][] testAnswers = new char[50][5];
try (Scanner input = new Scanner(Paths.get(filename))) {
for(int row = 0; row < testAnswers.length; row++) {
for(int col = 0; col < testAnswers[row].length; col++) {
String token = r.next();
if (token.length() != 1)
throw new IllegalArgumentException("Answers must be one character");
testAnswers[row][col] = token.charAt(0);
}
}
} catch (IOException ex) {
System.err.println("Error reading file: " + ex.getMessage());
System.exit(1);
}
String filename = "ArrayHW2.txt";
int numTests = 6;
char[][] testAnswers = new char[50][5];
//char[] key = new char[4];
Scanner input = null;
try
{
input = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening File");
System.exit(1);
}
int counter = 0;
while(scanner.hasNext())
{
copyString(testAnswers[counter], scanner.nextLine());
}
input.close();
its been a while i haven't code in java and im not sure about the methods but consider it a pseudo code .
you can use this copy :
void copyString(char[] arr, String x)
{
int size = x.length();
for (int i=0; i<size; i++){
arr[i] = x.CharAt(i);
}

Unable to scan all the elements of the string array using scanner in java

I am unable to scan all the elements of the string array in Java. I don't know what is the error.. please help
I'm unable to scan the first element of the array.its not even showing an error.
import java.util.*;
public class uhu {
public static void main(String[] args) {
System.out.println("Hit n");
Scanner sc = new Scanner(System.in);
try {
int n = sc.nextInt();//scan the size of the array
String[] str=new String[n];
System.out.println("Enter elements");
for (int i = 1; i < n; i++) //scanning the elements
{
str[i]=sc.nextLine();
}
for (int i = 0; i < n; i++) //printing all the elements
{
System.out.println(str[i]);
}
} finally {
if (sc != null)
sc.close();
}
}
}
Here you go :
System.out.println("Enter elements");
for (int i = 0; i < n; i++) //scanning the elements
{
str[i]= sc.next();
}
start from i=0 and use next() instead of nextLine().
In case you want to read whole lines then a BufferedReader will do the job, here in our case Scanner nextLine() is skipping the last line or taking a blank line as input at the end.
Use BufferedReader to get your job done.
System.out.println("Hit n");
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
try {
int n = Integer.parseInt(buf.readLine());//scan the size of the array
String[] str=new String[n];
System.out.println("Enter elements");
for (int i = 0; i < n; i++) //scanning the elements
{
str[i]= buf.readLine();
}
for (int i = 0; i < n; i++) //printing all the elements
{
System.out.println(str[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (buf != null)
buf.close();
}

How do you store each value separately using comma then they store into separate array?

A simple data file which contains
1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
Each line represents a season of premiership and has the following format: year, premiers, runners up, minor premiers, wooden spooners, Grand Final held, winning score,
losing score, crowd
I know how to store a data into an array and use the delimiter, but I am not exactly sure how to store EACH data item by a comma into separate arrays? Some suggestions and what particular code to be used would be nice.
UPDATE:
I just added the code but it still didn't work. Here's the code:
import java.io.*;
import java.util.Scanner;
public class GrandFinal {
public static Scanner file;
public static String[] array = new String[1000];
public static void main(String[] args) throws FileNotFoundException {
File myfile = new File("NRLdata.txt");
file = new Scanner (myfile);
Scanner s = file.useDelimiter(",");
int i = 0;
while (s.hasNext()) {
i++;
array[i] = s.next();
}
for(int j=0; j<array.length; j++) {
if(array[j] == null)
;
else if(array[j].contains("Y"))
System.out.println(array[j] + " ");
}
}
}
Here you go. Use ArrayList. Its dynamic and convenient.
BufferedReader br = null;
ArrayList<String> al = new ArrayList();
String line = "";
try {
br = new BufferedReader(new FileReader("NRLdata.txt"));
while ((line = br.readLine()) != null) {
al.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
What does not work in your case ?
Because your season array is empty. You need to define the length, for ex:
private static String[] season = new String[5];
This is not right because you don't know how many lines you are going to store. Which is why I suggested you to Use ArrayList.
After working around a bit, I have come up with following code:
private static File file;
private static BufferedReader counterReader = null;
private static BufferedReader fileReader = null;
public static void main(String[] args) {
try {
file = new File("C:\\Users\\rohitd\\Desktop\\NRLdata.txt");
counterReader = new BufferedReader(new FileReader(file));
int numberOfLine = 0;
String line = null;
try {
while ((line = counterReader.readLine()) != null) {
numberOfLine++;
}
String[][] storeAnswer = new String[9][numberOfLine];
int counter = 0;
fileReader = new BufferedReader(new FileReader(file));
while ((line = fileReader.readLine()) != null) {
String[] temp = line.split(",");
for (int j = 0; j < temp.length; j++) {
storeAnswer[j][counter] = temp[j];
System.out.println(storeAnswer[j][counter]);
}
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
I have added counterReader and fileReader; which are used for counting number of lines and then reading the actual lines. The storeAnswer 2d array contains the information you need.
I hope the answer is better now.

Categories