我想阅读文件" Lab5File1.dat"并将其内容写入" test.dat"。
我创建了一个arraylist,因为我后来想要读取无限数量的文件。
但是我收到以下错误:
java.io.EOFException
at java.io.DataInputStream.readInt(Unknown Source)
at FileRead$FileReadThread.run(FileRead.java:101)
我的代码如下:
public class FileRead {
private static final String String = null;
static String file="Lab5File1.dat";
static String output="test.dat";
ArrayList<Thread> threadList = new ArrayList<Thread>();
static DataOutputStream dosZip;
public static void main(String[] args) {
// TODO Auto-generated method stub
new FileRead();
}
public FileRead()
{
Thread newThread;
try{
dosZip = new DataOutputStream(new FileOutputStream( output ));
} catch(IOException fnf){
System.out.println("Trouble creating "+output );
fnf.printStackTrace();
System.exit(2);
}
newThread = new FileReadThread("Lab5File1.dat");
threadList.add( newThread );
newThread.start();
// Wait for all the threads to finish
for( Thread th: threadList){
try{
th.join();
} catch(InterruptedException ie){
System.out.println("Thread interrupted");
}
}
// flush & close the combined file
try {
dosZip.flush();
dosZip.close();
} catch(IOException ioe){
System.out.println("Trouble flushing and closing file.");
ioe.printStackTrace();
System.exit(3);
}
}
public static class FileReadThread extends Thread {
String inputFileName;
public FileReadThread(String fileName)
{
inputFileName = file;
}
public void run()
{
InputStream is = null;
DataInputStream dis = null;
System.out.println("TRYING.........");
try{
// create input stream from file input stream
is = new FileInputStream(inputFileName);
// create data input stream
dis = new DataInputStream(is);
while ( true )
{
int Zip = dis.readInt();
String City = dis.readUTF();
String State = dis.readUTF();
double Longitude =dis.readDouble();
double Latitudes=dis.readDouble();
int Zone = dis.readInt();
int dst = dis.readInt();
dosZip.writeInt(Zip);
dosZip.writeUTF(City);
dosZip.writeUTF(State);
dosZip.writeDouble(Longitude);
dosZip.writeDouble(Latitudes);
dosZip.writeInt(Zone);
dosZip.writeInt(dst);
}
}catch(Exception e){
// if any I/O error occurs
e.printStackTrace();
}finally{
// releases any associated system files with this stream
if(is!=null)
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(dis!=null)
try {
dis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}}
答案 0 :(得分:1)
在Java中,将一个文件的内容复制到另一个文件的最简单方法之一是使用FileChannel类
如果你想阅读文件&#34; Lab5File1.dat&#34;并将其内容写入&#34; test.dat&#34;尝试使用以下代码(如果您使用早于7的Java,请使用try-finally块来正确关闭通道):
try (FileChannel src = new FileInputStream("Lab5File1.dat").getChannel();
FileChannel dest = new FileOutputStream("test.dat").getChannel()){
dest.transferFrom(src, 0, src.size());
} catch (IOException e) {
e.printStackTrace();
}