使用FileInputStream从一个文件读取并使用FileOutputStream写入另一个文件

时间:2014-03-09 12:56:27

标签: java

我试图从一个文件中读取并使用title中指定的类将读取的字节写入另一个文件。我成功地做到了但是当我尝试尝试不同的东西时,我遇到了一个我不明白的问题。

这是代码

import java.io.*;
public class FileInputStreamDemo {

    public static void main(String[] args)
            throws Exception {
        // TODO Auto-generated method stub
        int size;
        InputStream f = new
                FileInputStream("G:/Eclipse Workspace/FileInputStream Demo/src/FileInputStreamDemo.java");

        System.out.println("Total available bytes: " + (size = f.available()));
    /*int n=size/40;
    System.out.println("first " + n + " bytes of file one read() at a time");

    for (int i=0;i<n;i++)
    {
        System.out.print((char) f.read());
    }
    System.out.println("\n Still available: " + f.available());
    System.out.println("reading the next" + n + "with one read(b[])");
    byte b[] = new byte[n]; */
    /*for(int i=0;i<size;i++)
    {
        System.out.print((char) f.read());
    }*/
        OutputStream f1 = new
                FileOutputStream("G:/Eclipse Workspace/FileInputStream Demo/test.txt");
        for (int count = 0; count < size; count++) {
            f1.write(f.read());
        }
        for (int i = 0; i < size; i++) {
            System.out.print(f.read());
        }

        f.close();
        f1.close();
    }
}

我所说的问题是,当我第一次阅读FileInputStream对象ff.read()并将其写入f1即{{1}时对象继续执行它的意图,但是当我再次尝试读取它时,它返回-1。为什么呢?

1 个答案:

答案 0 :(得分:1)

使用RandomAccessFile和seek(0)方法在开头回来。

RandomAccessFile file = new RandomAccessFile(new File("G:/Eclipse Workspace/FileInputStream Demo/src/FileInputStreamDemo.java"), "r");

以下是示例代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

public class FileInputStreamDemo {

    public static void main(String[] args) throws Exception {
        long size;
        File file = new File("D:/Workspace/JavaProject/src/com/test/FileInputStreamDemo.java");
        RandomAccessFile f = new RandomAccessFile(file, "r");

        System.out.println("Total available bytes: " + (size = file.length()));
        OutputStream f1 = new FileOutputStream(new File(
                "D:/Workspace/JavaProject/resources/test.txt"));
        for (int count = 0; count < size; count++) {
            f1.write(f.read());
        }
        f.seek(0);
        for (int i = 0; i < size; i++) {
            System.out.print((char)f.read());
        }

        f.close();
        f1.close();
    }
}