Reputation: 211
I have the following method that reads a file where it has an ID (int) and Content (String) separated by a tab. My method reads the file line by line, and using the tab delimiter, I parse the ID and the string into a doubly linked list like so:
void readAndAssemble(String fileName)
{
Scanner sc;
try
{
sc = new Scanner(new File(fileName));
while (sc.hasNextLine())
{
String line = sc.nextLine();
String lines[] = line.split("\t");
int packetID = Integer.parseInt(lines[0]);
// -----------------------------------------
String packetContent = lines[1]; // gives error in terminal
// -----------------------------------------
DLLNode curr = header.getNext();
DLLNode prev = header;
while (packetID > curr.getPacketID())
{
prev = curr;
curr = curr.getNext();
}
DLLNode newNode = new DLLNode(packetID, packetContent, prev, curr);
prev.setNext(newNode);
curr.setPrev(newNode);
}
sc.close();
} catch (FileNotFoundException e)
{
System.out.println("File does not exist");
}
}
This method works perfectly in Eclipse when I run it, but gives me this error when I use javac and run it in terminal:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at DLL.readAndAssemble(DLL.java:40)
at MessageAssembler.main(MessageAssembler.java:11)
Where my MessageAssembler class looks like this:
public class MessageAssembler
{
public static void main(String[] args)
{
DLL myDLL = new DLL();
myDLL.readAndAssemble("Mystery3.txt");
myDLL.printContent();
}
}
What could be causing this?
Upvotes: 0
Views: 2058
Reputation: 44854
It looks like you have lines in your file that do not conform to your understanding.
try doing
String lines[] = line.split("\t");
if (lines.length < 2) {
System.err.println ("error with line " + line);
continue;
}
There seems to be a problem with using Scanner on a unix
file
try
FileInputStream fstream = new FileInputStream("c:/temp/a.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
//Read File Line By Line
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println (line);
String [] lines = line.split ("\t");
if (lines.length < 2) {
System.err.println ("error with line " + line);
continue;
}
}
//Close the input stream
br.close();
Upvotes: 1