You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package persistence ;
import java.io.File ;
import java.io.FileNotFoundException ;
import java.util.Scanner ;
public class QuestionChecker {
public static boolean isDuplicate ( String username , String question ) {
File dir = new File ( username ) ;
if ( ! dir . exists ( ) ) return false ;
File [ ] files = dir . listFiles ( ) ; /*每次调用都获取一次文件列表*/
if ( files = = null ) return false ;
// 待查题目去掉空格,方便精确匹配
String target = question . trim ( ) ;
for ( File file : files ) { /* 遍历所有历史文件 */
if ( file . isFile ( ) & & file . getName ( ) . endsWith ( ".txt" ) ) {
try ( Scanner scanner = new Scanner ( file ) ) {
while ( scanner . hasNextLine ( ) ) {
String line = scanner . nextLine ( ) . trim ( ) ; /*遍历文件中的每一行 */
if ( line . isEmpty ( ) ) continue ; // 跳过空行
// 去掉题号部分(如 "1. ")
int dotIndex = line . indexOf ( '.' ) ;
if ( dotIndex ! = - 1 ) {
String storedQuestion = line . substring ( dotIndex + 1 ) . trim ( ) ;
// 精确匹配
if ( storedQuestion . equals ( target ) ) {
return true ;
}
}
}
} catch ( FileNotFoundException e ) {
e . printStackTrace ( ) ;
}
}
}
return false ;
}
}