Java项目中用File和Scanner读取同包文本文件失败求助
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 aNoSuchFileExceptionbecause the relative pathtest/fileTest.txtresolves against your project's root directory, not the package directory where your class lives. Plus, this method doesn't useFile/Scanneras required, so we can set this aside.Code 2 (ClassLoader.getResource)
TheNullPointerExceptionhappens becauseClassLoader.class.getResource()looks for files starting at the root of the classpath, not your class's package. Also, you were usingscanner.toString()which prints the Scanner object itself, not the actual file content—that's a common misstep!Code 3 (Relative Path with ../)
TheFileNotFoundExceptionis caused by the relative path../test/fileTest.txtnot 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.xmlto copy.txtfiles 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

