2017-04-08 4 views
0

그래서 사용자의 파일 이름을 허용하고 싶습니다. 그런 다음 문자열의 마지막 네 문자가 ".txt"인지 확인하려고합니다. 일치하지 않으면 사용자 입력 문자열의 끝에 ".txt"를 추가하십시오. 그럴 경우 건너 뜁니다. 단순한.If 문이 파일 이름 정확성 검사 (".txt"추가)가 작동하지 않습니다.

하지만 작동하지 않습니다. "examplataata.txt"를 입력해도 여전히 ".txt"가 추가되고 FileNotFoundException이 발생합니다. 이유는 알 수 없습니다. 나는 같은 계산을하고 그것을 인쇄/디버거에서 확인; 부분 문자열에 대한 내 메서드 호출이 정확합니다.

관련 코드 :!

import java.util.*; 
import java.io.*; 

public class MappingApp { 
    public static void main(String[] args) { 
     Scanner sc = new Scanner(System.in); 
     String userInput; 
     System.out.print("Enter file to read from: "); 
     userInput = sc.nextLine(); 

     if ((userInput.substring(userInput.length()-4, userInput.length())) != ".txt") { 
      userInput += ".txt"; 
     } 

     try { 
      File f = new File(userInput); 
      BufferedReader br = new BufferedReader(new FileReader(f)); 
     } 
     catch (FileNotFoundException e) { 
      System.err.println(e); 
     } 
    } 
} 
+3

Java String API의 endsWith 메소드를 사용하여 userInput이 ".txt"로 끝나는 지 확인할 수 있습니다. –

답변

0

보통이 같은 문자열을 비교하지 않는 = 또는 == 이 도움이 될

if (!(userInput.substring(userInput.length()-4, userInput.length()).equals (".txt")) 

희망에

if ((userInput.substring(userInput.length()-4, userInput.length())) != ".txt") 

을 변경해보십시오.