0

I try several times to convert the text in a File into List and print some elements of the List according to reference index but I can't, it throws Index Out Of Bounds Exception: index 3 , Size 1

is there any possible way to overcome the situation.

myTEXT.txt

PETTY MIND,2023,IS,COMMING

my Code

List<String> TexttoList = new ArrayList<String>();
    
    FileReader myTEXT = new FileReader("myTEXT.txt");
    
    Scanner scanText = new Scanner(myTEXT);
    scanText.useDelimiter(",\\s*");
    
    while(scanText.hasNext()) {
        
        
        for(int d = 0; d<4; d++){
        TexttoList.add(d , scanText.next());
        System.out.println(TexttoList.get(3));
        //IndexOutOfBounds Exception: index 3 , Size 1
        }
    }
    

it only prints First index(0) and return the entire text

    PETTY MIND
    2023
    IS
    COMMING
    
2
  • 1
    Hello. What is myTEXT in new Scanner(myTEXT);? Note that FileReader which is set to read from myTEXT.txt file is named FileReader scores. Please use edit option and clarify/correct your question so we wouldn't waste your (and our) time on unrelated problems. Commented Jan 15, 2023 at 0:22
  • 2
    Anyway regarding IndexOutOfBounds Exception: index 3 , Size 1 please carefully read your for loop. Note that in its first iteration you are adding one element to TexttoList, but immediately after that, you are trying to read value from position 3, which doesn't exist yet. Maybe you wanted to read it after your loop finished reading all data. Commented Jan 15, 2023 at 0:26

1 Answer 1

1

You can use the NIO API

Java NIO (New IO) is an alternative IO API for Java

var list = Files.readString(Paths.get("myText.txt")).split(",\\s*"); 

Code explanation:

  • Files.readString()

Reads all content from a file into a string, decoding from bytes to characters using the UTF-8 charset. The method ensures that the file is closed when all content have been read or an I/O error, or other runtime exception, is thrown.

  • Paths.get()

Converts a path string, or a sequence of strings that when joined form a path string, to a Path

  • split(): split the content of the file (the returned string from the method Files.readString) and returns array of string.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.