Splitting error- IndexOutOfBoundsException - java

I got stuck with an issue, that I can't seem to solve. When splitting I should be able to get id, name, check by setting row[0], row[1], row[2]. Strangely only row[0] (id) seem to work. Name, check gives me an error. Could someone help me further?
Example of data:
id,name,check
1,john,0
1,patrick,0
1,naruto,0
Code:
ArrayList<String> names = new ArrayList<String>();
try {
DataInputStream dis = new DataInputStream(openFileInput(listLocation(listLoc)));
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split(Pattern.quote(","));
//names.add(row[0]); // id
names.add(row[1]); // name // ERROR AT THIS LINE
//names.add(row[2]); // check
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
Error message:
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
Solved
It seems I had an incorrect value (question marks) at end of file. When removing this line. My code worked (without Patter.quote). Thank you all for fast reply's. First answer helped me on reminding me of using Log value where I could see the 'incorrect value'. My bad.

Probably in the time:
String[] row = line.split(",");
was called, there was no comma (,) in the line of the file/stream you're trying to read.

Try this code,
ArrayList<String> names = new ArrayList<String>();
try {
DataInputStream dis = new DataInputStream(openFileInput(listLocation(listLoc)));
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split(",");
//names.add(row[0]); // id
names.add(row[1]); // name // ERROR AT THIS LINE
//names.add(row[2]); // check
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
I think you don't need to use Pattern.quote(",") here.

In my experience with txt files this is the best way of dealing with it:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class Cyto {
public static void main(String[] args) throws IOException {
ArrayList<String> names = new ArrayList<String>();
try {
FileInputStream dis = new FileInputStream("list.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while (br.ready()) {
line = br.readLine();
String[] row = line.split(Pattern.quote(","));
System.out.println(row[1]);
names.add(row[1]);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use
br.ready()
instead of reading directly from stream.

Related

Why has this file I/O operation in Java caused NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I was writing code for a small tool that removes a user-given string from a file whose name is fed to the program from the command line. But when run, it throws a NullPointerException. I can't figure out why. Please help me solve this mystery. Thank you very much. This code is as follows.
/**
* Remove certain lines from a text file.
*/
import java.util.*;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class LineCutter {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java LineCutter filename");
System.exit(1);
}
System.out.println("Enter the line to be removed:");
Scanner lineToRemove = new Scanner(System.in);
lineToRemove.nextLine();
FileReader fr = null;
FileWriter fw = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
fr = new FileReader(args[1]);
br = new BufferedReader(fr);
fw = new FileWriter(new File("output.txt"));
bw = new BufferedWriter(fw);
String line = br.readLine();
while(line != null) {
if (!line.equals(lineToRemove))
bw.write(line);
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
br.close(); // NullPointerException
fw.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Operations finished.");
}
}
If fr = new FileReader(args[1]) throws an exception then br will be null when you attempt to call br.close() and the NullPointerException will hide the actual problem. Your problem is most likely the use of 1 as the index causing an ArrayIndexOutOfBoundsException. You expect only one element in the args array, so you should be using args[0]. Remember, arrays are zero-based.
Also, you should be using a try-with-resources statement. It handles closing everything for you automatically in a null-safe manner. For example:
try (BufferedReader br = new BufferedReader(new FileReader(args[0]));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")))) {
// I/O code...
} catch (IOException ex) {
ex.printStackTrace();
}
Not sure what the following code is supposed to be doing:
System.out.println("Enter the line to be removed:");
Scanner lineToRemove = new Scanner(System.in);
lineToRemove.nextLine();
You don't do anything with result of lineToRemove.nextLine(). Though later you test if a String is equal to lineToRemove, which will always be false. Perhaps you mean:
String lineToRemove = new Scanner(System.in).nextLine();
Probably because fr = new FileReader(args[1]); is throwing an exception (probably because it can't find the file specified in args[1]), and so br continue to be null, and so you are invoking .close() in a null object.
I would also point out that here:
if (!line.equals(lineToRemove))
bw.write(line);
you are invoking equals between a String and a Scanner

Java reading words into ArrayList of Strings [duplicate]

This question already has answers here:
Java reading a file into an ArrayList?
(13 answers)
Closed 6 years ago.
I would like to read in a file (game-words.txt) via a buffered reader into an ArrayList of Strings. I already set up the buffered reader to read in from game-words.txt, now I just need to figure out how to store that in an ArrayList. Thanks ahead for any help and patience!
Here is what I have so far:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOExecption;
class Dictionary{
String [] words; // or you can use an ArrayList
int numwords;
// constructor: read words from a file
public Dictionary(String filename){ }
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("game-words.txt"));
while ((line = br.readLine()) != null){
System.out.println(line);
}
} catch (IOExecption e) {
e.printStackTrace();
}
}
Reading strings into array:
Automatic:
List<String> strings = Files.readAllLines(Path);
Manual:
List<String> strings = new ArrayList<>();
while ((line = br.readLine()) != null){
strings.add(line);
}
Splitting lines to words (if one line contains several words):
for(String s : strings) {
String[] words = s.split(" "); //if words in line are separated by space
}
This could be helpful too:
class Dictionary{
ArrayList<String> words = new ArrayList<String>(); // or you can use an ArrayList
int numwords;String filename;
// constructor: read words from a file
public Dictionary(String filename){
this.filename =filename;
}
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("game-words.txt"));
while ((line = br.readLine()) != null){
words.add(line.trim());
}
} catch (IOExecption e) {
e.printStackTrace();
}
}
I have used trim which will remove the leading and the trailing spaces from the words if there are any.Also, if you want to pass the filename as a parameter use the filename variable inside Filereader as a parameter.
Yes, you can use an arrayList to store the words you are looking to add.
You can simply use the following to deserialize the file.
ArrayList<String> pList = new ArrayList<String>();
public void deserializeFile(){
try{
BufferedReader br = new BufferedReader(new FileReader("file_name.txt"));
String line = null;
while ((line = br.readLine()) != null) {
// assuming your file has words separated by space
String ar[] = line.split(" ");
Collections.addAll(pList, ar);
}
}
catch (Exception ex){
ex.printStackTrace();
}
}

search a word inside file then stored in array

my problem is i read a file then i search a word "(:types"
i want take the words after "(:types" but the code take a line after "(:types"
this is the problem i need to you to find why my code cant store words after
"(:types" ( my code take "
location vehicle cargo)" i need to take ( "space fuel
location vehicle cargo")
sorry for my English
(:types space fuel
location vehicle cargo)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;
public class type2 {
public static void main(String[] args){
String filePath = "C:\\test4.txt";
BufferedReader br;
String line = "";
String read=null;
List<String> temps = new LinkedList<String>();
try {
br = new BufferedReader(new FileReader(filePath));
try {
while((line = br.readLine()) != null)
{
String[] words = line.split(" ");
for (String word : words) {
if (word.equals("(:types") ) {
while((read = br.readLine()) != null){
temps.add(read);
if (word.equals("(:predicates") );
break;
}
String[] tempsArray = temps.toArray(new String[0]);
String [] type=tempsArray[0].split(" ");
System.out.println(tempsArray[0]);
}
}
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The reason you aren't getting the words that are on the same line is because you don't parse the rest of the line.
First you get the first line with
while((line = br.readLine()) != null)
And then split that on all the spaces with:
String[] words = line.split(" ");
But once you find the string (:types, all you do is start reading from the file again. You never parse the remaining parts of the array words.
If you want to parse the rest of this array, maybe find the index of the string (:types in your array, then just parse all parts after it.
The problem seem very straightforward.
If I understand you correctly you have a file which contain the lines:
(:types space fuel
location vehicle cargo)
You want to find the line containing "(:types" and then save "space" and "fuel".
In your code your read in a new line of text like this
while((line = br.readLine()) != null)
You check line for whether it contains (:types and if it does you store the words in the next line through the code:
while((read = br.readLine()) != null){
temps.add(read);
This above is your problem. To fix this you should change the above code to the following:
for (String word : words){
if(!word.equals("(:types")){
temps.add(read);
}
}

Reading lines with BufferedReader and checking for end of file

If I have something like this in my code:
String line = r.readLine(); //Where r is a bufferedReader
How can I avoid a crash if the next line is the end of the file? (i.e. null)
I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.
If there is something there then all is OK, but I can't be guaranteed that there will be something there.
So if I do something like: (pseudo code):
if (r.readLine is null)
//End code
else {check line again and excecute code depending on what the next line is}
The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?
I've not worked out a way to do this - any suggestions would be a great help.
Am... You can simply use such a construction:
String line;
while ((line = r.readLine()) != null) {
// do your stuff...
}
If you want loop through all lines use that:
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
You can use the following to check for the end of file.
public bool isEOF(BufferedReader br)
{
boolean result;
try
{
result = br.ready();
}
catch (IOException e)
{
System.err.println(e);
}
return result;
}
In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.
String line = r.readLine();
while(line!=null){
System.out.println(line);
line = r.readLine();
}
A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class LineOperation {
public static void main(String[] args) throws IOException {
Files.newBufferedReader(Paths.get("C://xyz.txt")).
lines().
collect(Collectors.toSet()). // You can also use list or any other Collection
forEach(System.out::println);
}
}
You can do it via BufferReader. I know this is not relevant to following question. But I would post it for extra fact for a newbie who would not use BufferReader but Scanner for reading file.
A part from BufferReader you could use Java Scanner class to read the file and check the last line.
Buffer Reader
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line
}
}
Scanner
try {
Scanner scanner = new Scanner(new FileReader(file));
while (scanner.hasNext()) {
// Above checks whether it has or not ....
}
} catch (IOException e) {
e.printStackTrace();
}
If you use this code fragment in a multi threaded environment, go ahead with BufferReader since its synchronized.
In addition, BufferReader is faster than Scanner.
If you would like to do some check like:
if (reader.ready())
stringBuilder.append("#");
You can use ready()
public static void check() throws IOException {
InputStream in = new FileInputStream(new File(filePath));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
if (reader.ready())
stringBuilder.append("#");
}
String returnedString = stringBuilder.toString();
System.out.println(returnedString);
}
You could purposely have it throw the error inside your loop. i.e.:
String s = "";
while (true) {
try {
s = r.readline();
}catch(NullPointerException e) {
r.close();
break;
}
//Do stuff with line
}
what everyone else has sad should also work.

Delete Specific Line From Java Text File?

I want to delete a specific line from a text file. I found that line, but what to do next?
Any idea?
Read file from stream and write it to another stream and skip the line which you want to delete
There is no magic to removing lines.
Copy the file line by line, without the line you don't want.
Delete the original file.
rename the copy as the original file.
Try this code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class Solution {
public static void main(String[] args) throws FileNotFoundException, IOException{
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
Try to read file:
public static String readAllText(String filename) throws Exception {
StringBuilder sb = new StringBuilder();
Files.lines(Paths.get(filename)).forEach(sb::append);
return sb.toString();
}
then split text from specific character (for new line "\n")
private String changeFile(){
String file = readAllText("file1.txt");
String[] arr = file.split("\n"); // every arr items is a line now.
StringBuilder sb = new StringBuilder();
for(String s : arr)
{
if(s.contains("characterfromlinewillbedeleted"))
continue;
sb.append(s); //If you want to split with new lines you can use sb.append(s + "\n");
}
return sb.toString(); //new file that does not contains that lines.
}
then write this file's string to new file with:
public static void writeAllText(String text, String fileout) {
try {
PrintWriter pw = new PrintWriter(fileout);
pw.print(text);
pw.close();
} catch (Exception e) {
//handle exception here
}
}
writeAllText(changeFile(),"newfilename.txt");
Deleting a text line directly in a file is not possible. We have to read the file into memory, remove the text line and rewrite the edited content.
Maybe a search method would do what you want i.e. "search" method takes a string as a parameter and search for it into the file and replace the line contains that string.
PS:
public static void search (String s)
{
String buffer = "";
try {
Scanner scan = new Scanner (new File ("filename.txt"));
while (scan.hasNext())
{
buffer = scan.nextLine();
String [] splittedLine = buffer.split(" ");
if (splittedLine[0].equals(s))
{
buffer = "";
}
else
{
//print some message that tells you that the string not found
}
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("An error occured while searching in file!");
}
}

Categories

Resources