Reading text file into Java array [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
So I'm trying to take a series of "scores" from a text file to put into an array and then sort in order, rows of four, and write other methods to get the highest, lowest, average, etc. The println commands are in there but I haven't written the methods yet. I've been working all day and I'm starting to confuse myself, and now I'm getting a NullPointerException error in the main method. Any help?
package arrayops1d;
import java.io.*;
import java.util.*;
public class ArrayOps1D {
static int scores[];
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
BufferedReader reader = new BufferedReader(file);
String scores = "";
String line = reader.readLine();
while (line != null){
scores += line;
line = reader.readLine();
}
System.out.println(scores);
System.out.println(getTotal());
System.out.println(getAverage());
System.out.println(getHighest());
System.out.println(getLowest());
System.out.println(getMedian());
System.out.println(getPosition());
System.out.println(getDeviations);
System.out.println(getStdDev);
}

Here is one way you can read the int values from a file into an array of Integer using a Scanner and a List -
Integer[] scores = null;
File file = new File("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
if (file.exists() && file.canRead()) {
try {
List<Integer> al = new ArrayList<>();
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
al.add(scanner.nextInt());
} else {
System.out.println("Not an int: " + scanner.next());
}
}
scores = al.toArray(new Integer[al.size()]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("Can't find file: " + file.getPath());
}
if (scores != null) {
System.out.println("Scores Read: " + Arrays.toString(scores));
}

First Issue with your code:
In your file path, Instead using / , you must use \\ or better File.separator if your program wants to be ran in different platform.
If you do not , you will have java.io.FileNotFoundException
You are reading line by line, so you can use split Function and use Integer.paraseInt or Float.parseFloat to convert each splited elements and added to your array
How to use Split in Java
How to convert String to int

Related

how to print string array onto file? [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Convert array of strings into a string in Java
(14 answers)
Closed last month.
I have a string input file and I put the strings into arrays. I only want to print the last element of each string array onto my console and onto a output array. When I run my code, I get the last element of each string array onto my console, but see this on my output file:
[Ljava.lang.String;#51d5f7fd
How can I print the actual string array to show up on output file and not its string representation? I'll show you my code so you get a better understanding of what I'm trying to do:
try {
br = new BufferedReader(new FileReader("C:\\rd\\bubble.txt"));
//first, create new file object
File file = new File("C:\\rd\\bubble_out.txt");
if(file.exists()) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
String line = "";
while((line = br.readLine()) != null) { //while the line is not equal to null
String[] arr = line.split("\\s+"); //split at whitespace
System.out.println(arr[arr.length - 1]);
pw.println(arr);
pw.close();
}
}
catch(IOException x)
{
System.out.println("File not found");
}
}
}
}
}
I've tried using Array.toString() method, but I'm not sure how to implement it into my code correctly. I'm currently trying to do that, but if there's an easier way to do this, please let me know.
Use Arrays.toString to get a readable String representation of the array.
Don't close the PrintWriter inside the loop as you have not finished writing all output. You can use try with resources to avoid having to explicitly close it.
try (PrintWriter pw = new PrintWriter(file)) {
while((line = br.readLine()) != null) {
String[] arr = line.split("\\s+");
System.out.println(arr[arr.length - 1]);
pw.println(Arrays.toString(arr));
}
}

Add one whitespace at everyline of my txt file [duplicate]

This question already has answers here:
Writing in the beginning of a text file Java
(6 answers)
Closed 4 years ago.
I have this method that can read everything within a file but i need to be able to first add one whitespace before every new char at the beginning of everyline.
Tried to make it as easy as possible but non of it seem to work.
private static void write() throws IOException {
FileWriter fw = new FileWriter("C:\\Users\\karwa\\Desktop\\HistoryOfProgramming.txt");
for (int i = 0; i < 15; i++) {
fw.write(" ");
}
fw.close();
}
Used bufferedReader aswell that had a whileloop that was reading every line and adding one whitespace for each line but that didn't work either. Ideas?
you have to actualy read the lines and store them, only then can you add whitespace
public static void main(String... args) throws IOException {
File file = new File("test.txt");
Scanner fr = new Scanner(file);
List<String> lines = new ArrayList<>();
while (fr.hasNextLine()) {
lines.add(fr.nextLine());
}
PrintStream fw = new PrintStream(file);
for (String line : lines) {
fw.println(" " + line);
}
fr.close();
fw.close();
}
Read/write the contents to a string
Use replaceAll("\n", "\n ");

ArrayIndexOutOfBoundsException - Java - no loop print

I have a method that's reading a local CSV file and storing it in an array. I keep getting a ArrayIndexOutOfBoundsException when I try to print one of the index of the array.
The method:
public void getCsv() throws FileNotFoundException{
String fileName = "ADCSV.csv";
File file = new File(fileName);
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext()){
String data = inputStream.next();
//array of strings
String[] values = data.split(",");
System.out.println(values[4]);
}
inputStream.close();
}
All of the information in the csv is stored as general text. When I try to print this is the output:
"adminCount"
"1"
"0"
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at csvTest.test.getCsv(test.java:36)
at csvTest.test.main(test.java:19)
It starts to read the values from that particular column fine. It then errors out.
I feel like I've been looking at the problem for awhile now and looking right past the issue.
Thanks
Change your method to:
public void getCsv() throws FileNotFoundException {
String fileName = "ADCSV.csv";
File file = new File(fileName);
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data = inputStream.next();
// array of strings
String[] values = data.split(",");
if (values.length < 5) {
System.err.println("not enough values: ");
for (int i = 0; i < values.length; i++) {
System.err.println("value " + i + ": " + values[i]);
}
continue;
}
System.out.println(values[4]);
}
inputStream.close();
}
That should show the problem. I mean it will print out the values of the line where the error will occur. Since we don't know what exactly produced the error this will be a start. Maybe somewhere is a comma where it shouldn't be or it is missing.
If the content of the local CSV file can contain errors then it would be appropriate to check the length of the splitted line and set up an error handling.

If-statement checking for filename correctness (appending ".txt") not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
So I want to accept a file name from the user. I then want to check if the last four characters of the string are ".txt". If they aren't, append ".txt" to the end of the user inputted string. If they are, skip. Simple.
But it's not working - when I enter "exampledata.txt" it still adds ".txt" and throws a FileNotFoundException - and I can't figure out why. I've taken the same calculation and printed it out/verified in debugger; my method call to substring is correct.
Relevant code:
import java.util.*;
import java.io.*;
public class MappingApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userInput;
System.out.print("Enter file to read from: ");
userInput = sc.nextLine();
if ( (userInput.substring(userInput.length()-4, userInput.length())) != ".txt" ) {
userInput += ".txt";
}
try {
File f = new File(userInput);
BufferedReader br = new BufferedReader(new FileReader(f));
}
catch (FileNotFoundException e) {
System.err.println(e);
}
}
}
Usually you don't compare strings as != or ==
Try changing
if ( (userInput.substring(userInput.length()-4, userInput.length())) != ".txt" )
to
if ( !(userInput.substring(userInput.length()-4, userInput.length()).equals (".txt") )
Hope this will help.

Print data from file to array

I need to have this file print to an array, not to screen.And yes, I MUST use an array - School Project - I'm very new to java so any help is appreciated. Any ideas? thanks
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class HangmanProject
{
public static void main(String[] args) throws FileNotFoundException
{
String scoreKeeper; // to keep track of score
int guessesLeft; // to keep track of guesses remaining
String wordList[]; // array to store words
Scanner keyboard = new Scanner(System.in); // to read user's input
System.out.println("Welcome to Hangman Project!");
// Create a scanner to read the secret words file
Scanner wordScan = null;
try {
wordScan = new Scanner(new BufferedReader(new FileReader("words.txt")));
while (wordScan.hasNext()) {
System.out.println(wordScan.next());
}
} finally {
if (wordScan != null) {
wordScan.close();
}
}
}
}
Nick, you just gave us the final piece of the puzzle. If you know the number of lines you will be reading, you can simply define an array of that length before you read the file
Something like...
String[] wordArray = new String[10];
int index = 0;
String word = null; // word to be read from file...
// Use buffered reader to read each line...
wordArray[index] = word;
index++;
Now that example's not going to mean much to be honest, so I did these two examples
The first one uses the concept suggested by Alex, which allows you to read an unknown number of lines from the file.
The only trip up is if the lines are separated by more the one line feed (ie there is a extra line between words)
public static void readUnknownWords() {
// Reference to the words file
File words = new File("Words.txt");
// Use a StringBuilder to buffer the content as it's read from the file
StringBuilder sb = new StringBuilder(128);
BufferedReader reader = null;
try {
// Create the reader. A File reader would be just as fine in this
// example, but hay ;)
reader = new BufferedReader(new FileReader(words));
// The read buffer to use to read data into
char[] buffer = new char[1024];
int bytesRead = -1;
// Read the file to we get to the end
while ((bytesRead = reader.read(buffer)) != -1) {
// Append the results to the string builder
sb.append(buffer, 0, bytesRead);
}
// Split the string builder into individal words by the line break
String[] wordArray = sb.toString().split("\n");
System.out.println("Read " + wordArray.length + " words");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
The second demonstrates how to read the words into an array of known length. This is probably closer to the what you actually want
public static void readKnownWords()
// This is just the same as the previous example, except we
// know in advance the number of lines we will be reading
File words = new File("Words.txt");
BufferedReader reader = null;
try {
// Create the word array of a known quantity
// The quantity value could be defined as a constant
// ie public static final int WORD_COUNT = 10;
String[] wordArray = new String[10];
reader = new BufferedReader(new FileReader(words));
// Instead of reading to a char buffer, we are
// going to take the easy route and read each line
// straight into a String
String text = null;
// The current array index
int index = 0;
// Read the file till we reach the end
// ps- my file had lots more words, so I put a limit
// in the loop to prevent index out of bounds exceptions
while ((text = reader.readLine()) != null && index < 10) {
wordArray[index] = text;
index++;
}
System.out.println("Read " + wordArray.length + " words");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
If you find either of these useful, I would appropriate it you would give me a small up-vote and check Alex's answer as correct, as it's his idea that I've adapted.
Now, if you're really paranoid about which line break to use, you can find the values used by the system via the System.getProperties().getProperty("line.separator") value.
Do you need more help with the reading the file, or getting the String to a parsed array? If you can read the file into a String, simply do:
String[] words = readString.split("\n");
That will split the string at each line break, so assuming this is your text file:
Word1
Word2
Word3
words will be: {word1, word2, word3}
If the words you are reading are stored in each line of the file, you can use the hasNextLine() and nextLine() to read the text one line at a time. Using the next() will also work, since you just need to throw one word in the array, but nextLine() is usually always preferred.
As for only using an array, you have two options:
You either declare a large array, the size of whom you are sure will never be less than the total amount of words;
You go through the file twice, the first time you read the amount of elements, then you initialize the array depending on that value and then, go through it a second time while adding the string as you go by.
It is usually recommended to use a dynamic collection such as an ArrayList(). You can then use the toArray() method to turnt he list into an array.

Categories

Resources