1

I've been trying to create a Java program to read a file "100.txt" that contains 100 integers and then store them into an int array. Later, I'm going to have it print the array and sort the numbers in the array, but I want to get it to read the text file and store the numbers in the array and convert it to an int array first. How do I do that?

I've tried a few different things. I know how to read a text file from a Scanner and create an array, but I've never changed the type (in this case, String to int). If any of you could help and give me some pointers on how to go about this, that would be much appreciated.

try { File file = new File("100.txt"); Scanner input = new Scanner(file); while (input.hasNextLine()) { String line = input.nextLine(); System.out.println(line); } input.close(); } catch (Exception ex) { ex.printStackTrace(); } int[] array = new int[file.length]; int i, n = array.length; for (i = 0; i < n; i++) { array[i] = Integer.parseInt(file[i]); } } 

2 Answers 2

1

Assuming that you know the number of lines your file has, you can use this code. Also note that it more efficient to read it as a BufferedReader and pass it to the scanner.

I have tried to keep it as simple as possible, but if you have any doubts feel free to ask.

public int[] readFile(String filePath)throws Exception { int[] array = new int[100]; Scanner sc = new Scanner(new BufferedReader(new FileReader(new File(filePath)))); for(int i=0;sc.hasNextLine();i++) { array[i]=Integer.parseInt(sc.nextLine()); } return array; } 
Sign up to request clarification or add additional context in comments.

1 Comment

If not, you should probably use a list and convert it to an int array
0

try this

public Integer[] ReadFromFile(String fileName) { List listInt = new LinkedList<Integer>(); try { Scanner input = new Scanner(new File(fileName)); while (input.hasNextLine()) { String value = input.nextLine(); listInt.add(Integer.parseInt(value)); System.out.println(value); } input.close(); } catch (Exception ex) { ex.printStackTrace(); } return (Integer[]) listInt.stream().toArray(); } 

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.