java - 文件 I/O : Reading from one file and writing to another (Java)

标签 java file io

我目前正在我的 cpe 类(class)的实验室工作,我们必须创建一个简单的程序来扫描 .txt 文件中的字符串并将它们打印到不同的 .txt 文件。到目前为止,我已经制定了基本程序,但是尽管我拥有所有必要的文件,但我的异常不断抛出。谁能帮我调试?

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

public class FileIO {

public static void main(String args[]) {        
    try {
        File input = new File("input");
        File output = new File("output");
        Scanner sc = new Scanner(input);
        PrintWriter printer = new PrintWriter(output);
        while(sc.hasNextLine()) {
            String s = sc.nextLine();
            printer.write(s);
        }
    }
    catch(FileNotFoundException e) {
        System.err.println("File not found. Please scan in new file.");
    }
}
}

最佳答案

您需要弄清楚它在哪里寻找“输入” 文件。当您仅指定 "input" 时,它会在当前工作目录 中查找文件。使用 IDE 时,此目录可能与您想象的不同。

尝试以下操作:

System.out.println(new File("input").getAbsolutePath());

查看它在哪里寻找文件。

关于java - 文件 I/O : Reading from one file and writing to another (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10588525/

相关文章:

java - CompoundIndex spring 不区分大小写

java - 从位于网络服务器上运行 java 程序。

c - 将文件读入链表时出现段错误

java - 如何查看书面文本文件的路径?

java - 为什么我的程序无法打开我的 .dat 文件?

java - 使用 Appium for java 的 ios UI 自动化。无法使用 xPath 找到元素

python - 尝试在 python 中打开并读取文件,但它创建并打开一个空文件

python - 如何删除目录中的所有文件,保持子目录完好无损

python - 如何使用 io 在内存中生成数据流作为文件之类的对象?

java - 如何在 testNG 文件中多次运行 SuiteTest