if语句检查文件名的正确性(追加" .txt")无法正常工作

时间:2017-04-08 04:04:07

标签: java substring

所以我想接受用户的文件名。然后我想检查字符串的最后四个字符是" .txt"。如果他们不是,请追加" .txt"到用户输入字符串的末尾。如果是,请跳过。简单。

但它不起作用 - 当我进入" exampledata.txt"它仍然添加" .txt"并抛出一个FileNotFoundException - 我无法弄清楚原因。我已经采取了相同的计算并在调试器中打印出来/验证了;我对substring的方法调用是正确的。

相关代码:

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);
        }
    } 
}

1 个答案:

答案 0 :(得分:0)

通常您不会将字符串比作!=或== 尝试更改

hasReplacement(word)

Pattern p = Pattern.compile("\\((.*?)\\)");
Matcher m = p.matcher(source);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    String word = m.group(1);
    String newWord = hasReplacement(word) ? replacement(word) : m.group(0);
    m.appendReplacement(sb, newWord); // appends the replacement, plus any not-yet-used text that comes before the match
}
m.appendTail(sb); // appends any text left over after the last match
String result = sb.toString();

希望这会有所帮助。