簡體   English   中英

如何從掃描儀讀取文本文件並將其轉換為整數數組 Java

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

我一直在嘗試創建一個 Java 程序來讀取包含 100 個整數的文件“100.txt”,然后將它們存儲到一個 int 數組中。 稍后,我將讓它打印數組並對數組中的數字進行排序,但我想讓它讀取文本文件並將數字存儲在數組中,然后先將其轉換為 int 數組。 我怎么做?

我嘗試了一些不同的東西。 我知道如何從 Scanner 讀取文本文件並創建一個數組,但我從未更改過類型(在本例中,String 為 int)。 如果你們中的任何人可以提供幫助並就如何解決這個問題給我一些指示,那將不勝感激。

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

假設您知道文件的行數,您可以使用此代碼。 另請注意,將其作為 BufferedReader 讀取並將其傳遞給掃描儀更有效。

我盡量保持簡單,但如果您有任何疑問,請隨時提出。

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

嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM