java 使用字符串参数调用方法

java calling method with string parameters

这里是初学者问题。此方法应从文本文件中读取一行,删除白色 space(并执行一些其他操作)并将该行打印到另一个文件。但是,当我打电话时:

noWhiteSpace(words.txt, clean.txt);

它不读取文件的内容。它只是将输入文件的名称写入新的输出文件:即 "clean.txt" 包含字符串 "words.txt" 而没有其他内容。我很困惑。

public static void noWhiteSpace(String inputFileName, String outputFileName) throws FileNotFoundException {

    Scanner inFile = new Scanner(inputFileName);
    PrintStream outFile = new PrintStream(outputFileName);

    while (inFile.hasNext()) {        
        String line = inFile.nextLine(); // read a line
        line = line.trim();              // eliminate the white space
        outputFile.println(line);        // print line to output file
    }
}

采用 String 参数的 Scanner 的构造函数并没有按照您的预期进行。我想你想要这样的东西:

File file = new File(inputFileName);
try {
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        // the rest of your code here
    }
    sc.close();
} 
catch (FileNotFoundException e) {
    e.printStackTrace();
}

阅读 Scanner API 上的 javadoc。

/* Constructs a new Scanner that produces values scanned from the specified string.
Parameters:
source - A string to scan 
*/
public Scanner(String source)

您需要将 File 实例而不是文件名传递给 Scanner 实例。

文件文件=新文件("path/to/file/on/disk"); 扫描仪 inFile = 新扫描仪(文件);

然后从扫描仪读取,如inFile.nextLine()等