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

如何将外部TXT文件文本与程序中定义的字符串对比?

Solution: Read File Content to String and Check for Target Match

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: character is an int holding a single character's Unicode value—you can't call contains() on it. We need the full file content as a String to use the contains() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:07:02