【问题标题】:java calling method with string parameters [duplicate]带有字符串参数的java调用方法[重复]
【发布时间】:2016-06-15 19:02:10
【问题描述】:

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

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

【问题讨论】:

  • 如果您的文件不是太大,您可以使用 FileUtils.readLines 和 FileUtils.writeLines 让您的生活更轻松
  • new Scanner(new File(inputFileName)) 怎么样?
  • 是的,根据@cwschmidt 和其他答案使用扫描仪。你只是传递字符串而不是文件。

标签: java methods static-methods


【解决方案1】:

带有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)

【讨论】:

  • 如果这回答了您的问题,请考虑为未来的用户“接受”它。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2014-03-23
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2012-02-21
    相关资源
    最近更新 更多