文件I / O:从一个文件读取并写入另一个文件(Java) [英] File I/O: Reading from one file and writing to another (Java)

查看:75
本文介绍了文件I / O:从一个文件读取并写入另一个文件(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在cpe类中的一个实验室工作,我们必须创建一个简单的程序,它从.txt文件中扫描字符串并将它们打印到另一个.txt文件。到目前为止,我已经绘制了基本程序,但是我的异常一直在扔,尽管我有所有必要的文件。任何人都可以帮我调试吗?

I'm currently working on a lab in my cpe class and we have to create a simple program that scans in strings from a .txt file and prints them to a different .txt file. So far I have the basic program drawn out but my exception keeps getting throw though I have all the necessary files. Can anyone help me debug?

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文件。当您只指定input时,它会在当前工作目录中查找该文件。使用IDE时,此目录可能不是您认为的目录。

You need to figure out where it looks for the "input" file. When you just specify "input" it looks for the file in the current working directory. When working with an IDE, this directory may not be what you think it is.

请尝试以下操作:

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

查看文件的查找位置。

这篇关于文件I / O:从一个文件读取并写入另一个文件(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆