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

Java项目中用File和Scanner读取同包文本文件失败求助

Fixing Same-Package Text File Reading with File and Scanner in Java

Hey there! Let's work through this file reading problem you're stuck on—since you're required to use File and Scanner, I'll break down why your previous attempts failed and show you a reliable solution.

First, Let's Diagnose Your Existing Code Issues

Let's go through each of your attempts to understand what went wrong:

  • Code 1 (NIO Files.readString)
    You got a NoSuchFileException because the relative path test/fileTest.txt resolves against your project's root directory, not the package directory where your class lives. Plus, this method doesn't use File/Scanner as required, so we can set this aside.

  • Code 2 (ClassLoader.getResource)
    The NullPointerException happens because ClassLoader.class.getResource() looks for files starting at the root of the classpath, not your class's package. Also, you were using scanner.toString() which prints the Scanner object itself, not the actual file content—that's a common misstep!

  • Code 3 (Relative Path with ../)
    The FileNotFoundException is caused by the relative path ../test/fileTest.txt not matching the actual location of your file relative to your project's working directory. This approach is fragile because working directories can change depending on how you run the program.

The Correct Approach for Same-Package Files

To reliably read a text file in the same package as your Java class using File and Scanner, follow these steps:

Step 1: Confirm File Placement

Make sure fileTest.txt is in the same directory as your Java class (e.g., if your class is com.example.MyReader, the file should be at src/main/java/com/example/fileTest.txt).

Step 2: Use Your Class's Resource Loader

Instead of ClassLoader.class.getResource(), use your class's own getResource() method—this looks for files starting in your class's package directory, which is exactly what you need.

Step 3: Read Content Correctly

Remember: scanner.toString() doesn't read file content! Use scanner.nextLine() (for line-by-line reading) or scanner.next() (if you need to split by spaces) to get the actual text.

Working Example Code

Here's a complete, tested example:

package com.example; // Replace with your actual package

import java.io.File;
import java.net.URI;
import java.net.URL;
import java.util.Scanner;

public class MyReader {
    public static void main(String[] args) {
        // Get the URL of the file in the same package
        URL fileUrl = MyReader.class.getResource("fileTest.txt");

        // Handle case where file isn't found
        if (fileUrl == null) {
            System.err.println("Error: Couldn't find fileTest.txt in the same package as MyReader!");
            return;
        }

        try {
            // Convert URL to File object
            File file = new File(fileUrl.toURI());
            
            // Initialize Scanner to read the file
            Scanner scanner = new Scanner(file);

            // Read line by line (swap to scanner.next() if you need space-separated values)
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }

            // Always close the scanner to free resources
            scanner.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Important Notes for Build Tools (Maven/Gradle)

If you're using Maven or Gradle, by default, non-Java files in src/main/java won't be copied to your compiled classpath. To fix this:

  • For Maven: Add this to your pom.xml to copy .txt files from your source directory:
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.txt</include>
                </includes>
            </resource>
        </resources>
    </build>
    
  • For Gradle: Add this to your build.gradle:
    sourceSets {
        main {
            resources {
                srcDirs = ['src/main/java']
                includes = ['**/*.txt']
            }
        }
    }
    

This ensures your text file gets packaged with your compiled classes, so the resource loader can find it even when you run the program outside your IDE.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:52:49