如何将外部TXT文件文本与程序中定义的字符串对比?
Got it, let's sort this out for you! The core issue here is that your character variable is just a single integer representing one character from the file—it doesn't have a contains() method (that's a String-exclusive method). To compare against your target string, we need to first read the entire file content into a single String, then we can easily check if it includes your defined string.
Here are two reliable approaches depending on your Java version:
Approach 1: Compatible with Java 7+ (Using BufferedReader)
This method uses BufferedReader to read lines efficiently, and StringBuilder to build the full file content safely. We also use try-with-resources to automatically close the reader (avoids resource leaks, which is far better than manually calling close()):
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileChecker { public static void main(String[] args) { String targetString = "username1"; StringBuilder fileContentBuilder = new StringBuilder(); // Try-with-resources auto-closes the reader when done try (BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\boung\\Desktop\\usernames.txt"))) { String line; // Read each line until end of file while ((line = reader.readLine()) != null) { fileContentBuilder.append(line).append(System.lineSeparator()); // Preserve line breaks } } catch (IOException e) { // Handle any IO errors (e.g., file not found) e.printStackTrace(); } // Convert the builder to a String String fileContent = fileContentBuilder.toString(); // Check if the target string exists if (fileContent.contains(targetString)) { System.out.println("Success: File contains '" + targetString + "'"); } else { System.out.println("Note: File does NOT contain '" + targetString + "'"); } } }
Approach 2: Java 11+ (Simplified with Files.readString)
If you're using Java 11 or newer, you can use the built-in Files.readString() method to read the entire file into a String in one line—super clean and concise:
import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class FileChecker { public static void main(String[] args) { String targetString = "username1"; try { // Read entire file content directly into a String String fileContent = Files.readString(Paths.get("C:\\Users\\boung\\Desktop\\usernames.txt")); // Check for the target string if (fileContent.contains(targetString)) { System.out.println("Success: File contains '" + targetString + "'"); } else { System.out.println("Note: File does NOT contain '" + targetString + "'"); } } catch (IOException e) { e.printStackTrace(); } } }
Key Notes:
- Why your original code didn't work:
characteris anintholding a single character's Unicode value—you can't callcontains()on it. We need the full file content as aStringto use thecontains()method. - Try-with-resources: Both examples use this to ensure the file reader is closed properly, even if an error occurs. This is a non-negotiable best practice for IO operations.
- Preserving line breaks: In Approach 1, we add
System.lineSeparator()after each line to keep the original file's line structure intact (optional, but useful if you need to match multi-line content).
内容的提问来源于stack exchange,提问作者dam1ne

