8

我目前正在我的 cpe 课程的实验室工作,我们必须创建一个简单的程序,从 .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.");
    }
}
}
4

5 回答 5

5

您需要弄清楚它在哪里查找"input"文件。当您只指定时,它会在当前工作目录"input"中查找文件。使用 IDE 时,此目录可能不是您认为的那样。

尝试以下操作:

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

查看它在哪里查找文件。

于 2012-05-14T17:58:11.470 回答
4

也许你只是忘记了flush()

       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);
            }
            **printer.flush();**
        }
        catch (FileNotFoundException e) {
            System.err.println("File not found. Please scan in new file.");
        }
于 2012-05-14T18:05:48.210 回答
3

使用 Java I/O 访问文件时,必须包含文件的文件类型扩展名(如果存在)。

    File input = new File("input.txt");
    File output = new File("output.txt");
于 2012-05-14T17:55:38.073 回答
0

我们可以通过使用FileInputStream对象读取文件并使用FileOutputStream对象写入另一个文件来做到这一点。

这是示例代码

package java_io_examples;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Vector;

public class Filetest {

   public static void main(String[] args) {

     try {

           FileInputStream fin = new FileInputStream("D:\\testout.txt");

           int i = 0;
           String s = "";

           while((i=fin.read())!=-1) {

               s = s + String.valueOf((char)i);

           }

           FileOutputStream fout = new 
           FileOutputStream("D:\\newtestout1.txt");
           byte[] b = s.getBytes();

           fout.write(b);
           fout.close();

           System.out.println("Done reading and writing!!");

      } catch(Exception e){
         System.out.println(e);
      }

    }

 }
于 2016-12-22T05:23:39.770 回答
0
public void readwrite() throws IOException 
{
    // Reading data from file
    File f1=new File("D:/read.txt");
    FileReader fr=new FileReader(f1);
    BufferedReader br=new BufferedReader(fr);

    String s = br.readLine();

    // Writing data
    File f2=new File("D:/write.txt");
    FileWriter fw=new FileWriter(f2);
    BufferedWriter bw=new BufferedWriter(fw);
    while(s!=null)
    {
        bw.write(s);
        bw.newLine();
        System.out.println(s);
        s=br.readLine();

    }
    bw.flush();
    bw.close();

}
于 2017-10-31T08:22:33.087 回答