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

Java中FileReader readLine返回null及库存文件修改功能问题

Fixing the readLine() Returning Null Issue in Your Java Inventory Modifier

Hey Luca, let's work through that frustrating readLine() returning null problem you're hitting with your inventory file code. I've run into similar file handling snags before, so let's break down what's going wrong and how to fix it.

First, Why Is readLine() Returning Null?

That null return usually boils down to a few common issues:

  • Wrong file path: Your program is looking for Magazzino.txt in the current working directory (not necessarily where your .java files are). If the file isn't there, FileReader will throw a FileNotFoundException—but if you're swallowing that exception without handling it, you might end up with a broken stream that returns null immediately.
  • Empty file: The file exists but has no content, so readLine() hits the end of the file right away.
  • Stream position/lock issues: If another part of your code (or another program like a text editor) has opened the file and moved the read pointer to the end, or locked the file, your BufferedReader can't access the content.
  • Resource leaks: An unclosed stream from a previous operation on the same file might leave the pointer in the wrong spot or lock the file.

Let's Fix the Code Properly

Also, a quick heads-up: You can't modify a text file in-place line by line easily with standard Java IO. You need to read all the content, make your changes in memory, then write everything back. Here's a revised version of your modifyAmount method that fixes the null issue and properly updates the inventory:

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class InventoryManager {
    public static void modifyAmount(String prodCode, String newAmount) {
        File magazzino = new File("Magazzino.txt");
        
        // Verify the file exists (and isn't a directory)
        if (!magazzino.exists() || magazzino.isDirectory()) {
            System.err.println("Error: Magazzino.txt doesn't exist or is a directory!");
            // Print absolute path to confirm where the program is looking
            System.out.println("Looking for file at: " + magazzino.getAbsolutePath());
            return;
        }

        List<String> updatedLines = new ArrayList<>();
        boolean productFound = false;

        // Use try-with-resources to auto-close the reader (prevents resource leaks)
        try (BufferedReader reader = new BufferedReader(new FileReader(magazzino))) {
            String currentLine;
            while ((currentLine = reader.readLine()) != null) {
                // Split line into product code and quantity (assuming whitespace separator)
                String[] lineParts = currentLine.split("\\s+");
                // Ensure the line has at least two fields before checking
                if (lineParts.length >= 2 && lineParts[0].equals(prodCode)) {
                    // Update quantity for matching product
                    updatedLines.add(prodCode + " " + newAmount);
                    productFound = true;
                } else {
                    // Keep non-matching lines as-is
                    updatedLines.add(currentLine);
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading the inventory file:");
            e.printStackTrace();
            return;
        }

        if (!productFound) {
            System.out.println("Warning: No product found with code " + prodCode);
            return;
        }

        // Write updated content back to the file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(magazzino))) {
            for (String line : updatedLines) {
                writer.write(line);
                writer.newLine();
            }
            System.out.println("Success! Updated product " + prodCode + " to quantity " + newAmount);
        } catch (IOException e) {
            System.err.println("Error writing to the inventory file:");
            e.printStackTrace();
        }
    }
}

Key Fixes & Improvements

  • Path verification: Checks if the file exists and prints its absolute path, so you can confirm the program is looking in the right location.
  • Try-with-resources: Automatically closes readers/writers, eliminating resource leaks that could cause weird stream behavior.
  • Proper file update flow: Reads all lines to memory, modifies the target line, then writes everything back—this is the standard, safe way to edit text files in Java.
  • Clear error handling: Catches and reports IO exceptions, so you know exactly what's going wrong (like permission issues, locked files, etc.).

Quick Troubleshooting Steps for the Null Issue

  1. Check the file path: Run the code above—it will print the absolute path of where it's looking for Magazzino.txt. Make sure your actual file is in that location.
  2. Inspect the file: Open Magazzino.txt and confirm it has valid content (each line with a product code and quantity, separated by whitespace).
  3. Close other programs: If you have the file open in Notepad, Excel, or another editor, close it—those programs can lock the file and prevent Java from reading it properly.

内容的提问来源于stack exchange,提问作者Luca Pasini

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:04:55