Reputation: 830
I have a similar problem.This is a snippet of my source:
FileWriter fstream = new FileWriter("results_for_excel.txt");
BufferedWriter writer = new BufferedWriter(fstream);
String sourceDirectory = "CVs";
File f = new File(sourceDirectory);
String[] filenames = f.list();
Arrays.sort(filenames);
String[] res = new String[filenames.length];
for (int i = 0; i < filenames.length; i++) {
System.out.println((i + 1) + " " + filenames[i]);
}
for (int i = 0; i < filenames.length; i++) {
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
res[i] = filenames[i].substring(beg,end);
System.out.println((i+1)+res[i]);
writer.write(res[i] + "\n");
}
writer.flush();
writer.close();
I get an exception at res[i] = filenames[i].substring(beg,end); I cant figure what's going on.Thanks in advance:) P.S I have read all the duplicates but nothing happened:(
Upvotes: 1
Views: 6100
Reputation: 830
The problem was at a KDE file called ".directory".Thank you very very much all of you:)
Upvotes: 0
Reputation: 14331
Add the following code after
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
This will display the filename that is in the wrong format;
if (beg == -1 || end == -1)
{
System.out.println("Bad filename: " + filenames[i]);
}
Upvotes: 1
Reputation: 33545
Either
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
is returning a -1
, its possible there's a file which doesn't contain either.
Upvotes: 1
Reputation: 47373
Either beg
or end
is -1. This means the filename doesn't contain -
or .
. Simple as that:)
Upvotes: 1
Reputation: 1634
One of characters in this code
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
is not found, so either beg
or end
equals -1. That's why you got the exception while calling substring
with negative arguments.
Upvotes: 0
Reputation: 4469
The error occurs, because a filename does not contain both '-' and '.'. In that case indexOf
returns -1
which is not a valid parameter for substring
.
Upvotes: 1