简体   繁体   中英

How to Read Text File From a Scanner and Convert Into an Int Array Java

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM