如何按名称读取java中的文本文件

如何按名称读取java中的文本文件,java,file,Java,File,我想输入文件名为file而不是file.txt。如何修改此代码 public static void main (String[] args) throws FileNotFoundException { Scanner sc = new Scanner(System.in); System.out.print("Enter the input file name: "); String newfile = sc.nextLine(

我想输入文件名为file而不是file.txt。如何修改此代码

public static void main (String[] args) throws FileNotFoundException {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter the input file name: ");
        String newfile = sc.nextLine();
}
字符串newfile将始终具有文件类型扩展名。。。
希望这有帮助。

我不确定您是想修改文件名还是读入文件。我猜是第二个

//Get filename
Scanner sc = new Scanner(System.in);
System.out.println("Enter the input file name: ");
String filename = sc.nextLine();
sc.close();

//Read file into StringBuilder
StringBuilder sb = new StringBuilder();
sc = new Scanner(new FileReader(new File(filename)));
while (sc.hasNextLine()){
  sb.append(sc.nextLine()).append(System.getProperty("line.separator"));
}

您想读取哪种类型的文件?您真的在问“如何将.txt扩展名添加到文件名?”。。。你试了什么?
//Get filename
Scanner sc = new Scanner(System.in);
System.out.println("Enter the input file name: ");
String filename = sc.nextLine();
sc.close();

//Read file into StringBuilder
StringBuilder sb = new StringBuilder();
sc = new Scanner(new FileReader(new File(filename)));
while (sc.hasNextLine()){
  sb.append(sc.nextLine()).append(System.getProperty("line.separator"));
}