You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术问询:编写读取含整数与字符串文件至ArrayList的UploadData方法及展示方法

Java File Reading & Display Task Solution

Hey there! Let's fix up your code and tick off all the required tasks properly. First, let's walk through the issues in your current uploadData method:

  • You’re calling scan.next() multiple times inside the loop, which skips chunks of your file content and leads to lost data
  • The end ArrayList you return is empty—you never actually add the read lines to it
  • Variable names like List don’t follow Java’s camelCase naming convention (should be something like dataList for clarity)
  • You’re not closing the file Scanner properly, which can cause unnecessary resource leaks

Step 1: Refined uploadData Method

We’ll adjust the method to correctly read every line from the file, store it in an ArrayList, and handle resources safely with try-with-resources. We’ll keep the user input for the filename as you had, but fix the core reading logic:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class FileDataHandler {

    // UploadData method with proper logic, returns ArrayList of file lines
    public static ArrayList<String> uploadData() throws IOException {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter the name of the file:");
        String fileName = keyboard.nextLine();
        keyboard.close(); // Close input scanner after getting filename

        ArrayList<String> dataList = new ArrayList<>();
        
        // Try-with-resources auto-closes the file scanner to avoid leaks
        try (Scanner fileScanner = new Scanner(new File(fileName))) {
            while (fileScanner.hasNextLine()) {
                String line = fileScanner.nextLine();
                dataList.add(line); // Add each full line to the ArrayList
            }
        }
        return dataList;
    }

Step 2: Content Display Method

Next, let’s add a displayData method that takes the ArrayList of read content and prints it in a clean, readable format:

// Method to display the read file content
    public static void displayData(ArrayList<String> data) {
        if (data.isEmpty()) {
            System.out.println("No data to display.");
            return;
        }

        System.out.println("\n--- File Content ---");
        int lineNum = 1;
        for (String line : data) {
            System.out.printf("%d. %s%n", lineNum++, line);
        }
    }

Step 3: Test with Main Method (Optional)

To tie everything together, add a main method to test the full workflow:

public static void main(String[] args) {
        try {
            ArrayList<String> fileData = uploadData();
            displayData(fileData);
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}

Key Improvements Breakdown

  • Try-with-resources: Guarantees the file scanner is closed automatically, preventing resource waste
  • Proper Data Storage: Every line from the file is added directly to the ArrayList, so no content is lost
  • Readable Naming: Variables like dataList and fileScanner make the code easier to follow and maintain
  • Error Handling: The main method catches IOException to handle common issues like missing files or permission errors

内容的提问来源于stack exchange,提问作者A Lexis Hill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:23:01