0

I'm trying to split each line from a text file into cells in an Array. Can I do it with split function and not count the lines in order to create an array?

I am using Scanner for reading files from Scanner. The file contains in each line the following format: number_number I want to save number_number as a string into a cell in Array. However, I don't know how many lines in my text file could be, in order to set an array size. I dont want to useLinkedList`, please use the assumption that will not have many lines. Is it possible to read from file and save each line into cell in array? There is no problem to change the method from Scanner to another one.

The problem in my code currently that it saves only the first line in my file.

public String[] readFromFileToStringArray(String s) { Scanner scanner = null; try { scanner = new Scanner(new File(s)); } catch (IOException e) { e.printStackTrace(); } String[] fileText = null; if (scanner != null) while (scanner.hasNext()) fileText = scanner.nextLine().split("\n"); return fileText; } 

3 Answers 3

2

When using scanner.nextLine() you read the text until the \n character, so the split you did is pointless since the line string won't have this character.

You can read all the file and then split it:

public String[] readFromFileToStringArray(String s) { String text = new String(Files.readAllBytes(Paths.get(s)), StandardCharsets.UTF_8); return text.split("\n"); } 

But really as the other answered said, it would probably be better to simply use List

Sign up to request clarification or add additional context in comments.

Comments

0

Should you change the way to add string to the array?

fileText.add(scanner.nextLine()); 

OR:

List<String> list = new ArrayList<String>(Arrays.asList(fileText)); list.addAll(Arrays.asList(scanner.nextLine().splite("\n"))); String[] fileText = list.toArray(); 

Comments

0
List<String> lines = Files.readAllLines(pathToFile); 

java Files is the easiest way for this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.