String index out of range: -1 - java

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:(

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]);
}

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.

Either beg or end is -1. This means the filename doesn't contain - or .. Simple as that:)

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.

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.

The problem was at a KDE file called ".directory".Thank you very very much all of you:)

Related

Java List Iterator for Binary File - Question

Is it possible to iterate through a binary file given a certain position specified by the user? I've been trying to think of a way to do this but I'm not finding any leads. Here is the code that I'm working on:
System.out.println("Enter name of file: ");
String filename = in.nextLine();
File file = new File(filename);
if (file.exists()) {
System.out.println(file.getAbsoluteFile());
RandomAccessFile raf = new RandomAccessFile(file, "r");
System.out.println("Size: " + file.length() + " bytes.");
System.out.println("Attempting to record file to AList");
AList<Byte> fileList = new AList<>();
raf.seek(0);
for (int i = 0; i < raf.length(); i++) {
fileList.add(raf.readByte());
}
System.out.print("Enter byte positon to navigate to: ");
long pos = in.nextLong();
in.nextLine();
ListIterator<Byte> itr = fileList.listIterator(0);
if (pos >= 0 && pos < file.length()){
int i = 0;
while(i < 5 && itr.hasNext() == true){
raf.seek(pos);
byte b = raf.readByte();
System.out.print(((b >= 0 && b <= 15)?"0":"") + Integer.toHexString((int)b & 0x00FF) + " ");
i++;
}
I'm not even entirely sure if what I've wrote is logically correct. What I'm trying to do is have the user specify a position in the binary file, then I check to see if thats within the files range. Then, it should be able to output the next 5 bytes from that position using an iterator. I'm not entirely sure about the iterator though.
You could just modify the loop reading the file to a) ignore the bytes up to the requested start position, b) read and print the next 5 bytes read, then c) exit.

How Add Strings from Multiple Text Files to Array

I have an string array of text file names. I would like to send this string array through an iterator and have it give me the first X number of characters of each text file. It would then put those strings in to an array that I can include in a list view.
I was planning on using a buffered reader to read the text and then substring it. But as for using the loops to go through each file, I am guessing that you would need to use a for loop or a foreach loop. However I am really unknowledgeable about how to use those.
Any help would be appreciated. Thanks!
Edit:
I should have added this earlier. I am using this to show what files have been downloaded and also to give them a preview of the text file. However, like I said above, some of them have not been downloaded. I would like to know which position in the filename array actually exist and to be able to put the retrieved strings in the proper places of the list view. Will this affect any of the current answers? Any ideas?
Let's name the variables you have:
String array: String filenames[]
x number of chars: int x
array of x chars in file: string chars[]. Assume you set each index to empty string.
import java.util.Scanner
public static void main(String[] args) {
Scanner fin = null;
// Loop through files
for(int i = 0; i < filenames.length; i++) {
// Open the file with a FileReader
fin = new Scanner(new BufferedReader(new FileReader(filenames[i])));
// Loop through x chars and add to string
for(int j = 0; j < x && fin.hasNext(); j++) {
chars[i] += fin.next();
}
// Close your file
fin.close();
}
}
Thanks for your help. This is what I ended up going with:
filenamearray = filenamefinal.split(";");
try {
List<String> results = new ArrayList<String>();
for (int i = 0; i < filenamearray.length; i++) {
File txt = new File(getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "/" + filenamearray[i] + ".txt");
if (txt.exists()) {
txtread = new FileInputStream(getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "/" + filenamearray[i] + ".txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(txtread));
String text = reader.readLine();
displaytxt = text.substring(0, 45) + ". . ."
results.add(displaytxt);
} else {
results.add("empty");
}
}
finalversetextarray = new String[results.size()];
finalversetextarray = results.toArray(finalversetextarray);

Reading method in java with starting and ending position gone wrong

So basically, I have an exam question that said "Add your directory to this method" and the follow up questions require that I use this method. My classmates that own macs, alongside with the examiner for some reason managed to get the file working.
public static String GetTextFromFile(int startPosition, int endPosition) {
String gotText = "";
String outText = "";
try {
Scanner fileInp = new Scanner(new File(
"C:/Users/Ted/Desktop/diary.txt"));
while (fileInp.hasNextLine()) {
gotText = gotText + fileInp.nextLine();
gotText = gotText + "\n";
}
// System.out.println(gotText);
for (int i = startPosition; i <= endPosition; i = i + 1) {
outText = outText + gotText.charAt(i - 1);
}
fileInp.close();
return outText;
} catch (IOException e) {
return outText;
}
}
I'm using a windows, why does this not work for me?
This is what an error says with an input of
Starting point 1 and ending point 9
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at java.lang.String.charAt(String.java:658)
at secretmessages.SecretMessages.GetTextFromFile(SecretMessages.java:78)
at secretmessages.SecretMessages.EveryNthCharacterSteganography(SecretMessages.java:199)
at secretmessages.SecretMessages.main(SecretMessages.java:322)
if you did not get any text from your fiel then gotText will still be "", so change this line
for(int i = startPosition; i <= endPosition; i = i + 1)
to
for(int i = startPosition; i <= endPosition && gotText.length () > 0; i = i + 1)
Also I would rather use String.substring
Also log your exceptions
catch(IOException e)
{
e.printStackTrace ();
return outText;
}
Issue in your code is you not check for empty string and use SrtingBuilder rather than String.check endPosition value.
endPosition value could not be greater than total length of string.
See following code may Resolve your Problem.
StringBuilder sb=new StringBuilder("");
while (fileInp.hasNextLine()) {
sb.append(fileInp.nextLine()).append("\n");
}
String gotText=sb.toString();
// System.out.println(gotText);
for (int i = startPosition; i <= endPosition; i = i + 1) {
outText = outText + gotText.charAt(i - 1);
}
if(!gotText.equals("")){
if(endPosition > gotText.length())
endPosition=gotText.length()-1;
for (int i = startPosition; i <= endPosition; i = i + 1) {
outText = outText + gotText.charAt(i - 1);
}
}
outText = outText + gotText.charAt(i - 1);
I think here if in the beginning i==0 then i-1 will throw the out of bound exception. And do check the endPosition it should not go beyond gotText.length().

CharBuffer.put() didn't working

I try to put some strings to CharBuffer with CharBuffer.put() function
but the buffer is left blank.
my code:
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
System.out.println(charBuf);
I tried to use with clear() or rewind() after allocate(1000) but that did not change the result.
Try this:
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.rewind();
System.out.println(charBuf);
The detail you're missing is that writing moves the current pointer to the end of the written data, so when you're printing it out, it's starting at the current pointer, which has nothing written.
Add a call to rewind() right after the loop.
You will need to flip() the buffer before you can read from the buffer. The flip() method needs to be called before reading the data from the buffer. When the flip() method is called the limit is set to the current position, and the position to 0. e.g.
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.flip();
System.out.println(charBuf);
The above will only print the characters in the buffers and not the unwritten space in the buffer.
You must rewind it after you put in the objects, try this
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.rewind();
System.out.println(charBuf);

Get the index of the start of a newline in a Stringbuffer

I need to get the starting position of new line when looping through a StringBuffer.
Say I have the following document in a stringbuffer
"This is a test
Test
Testing Testing"
New lines exist after "test", "Test" and "Testing".
I need something like:
for(int i =0;i < StringBuffer.capacity(); i++){
if(StringBuffer.chatAt(i) == '\n')
System.out.println("New line at " + i);
}
I know that won't work because '\n' isn't a character. Any ideas? :)
Thanks
You can simplify your loop as such:
StringBuffer str = new StringBuffer("This is a\ntest, this\n\nis a test\n");
for (int pos = str.indexOf("\n"); pos != -1; pos = str.indexOf("\n", pos + 1)) {
System.out.println("\\n at " + pos);
}
System.out.println("New line at " + stringBuffer.indexOf("\n"));
(no loop necessary anymore)
Your code works fine with a couple of syntactical modifications:
public static void main(String[] args) {
final StringBuffer sb = new StringBuffer("This is a test\nTest\nTesting Testing");
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '\n')
System.out.println("New line at " + i);
}
}
Console output:
New line at 14
New line at 19

Categories