文件写入
try {
FileOutputStream fileout = new FileOutputStream(f1);
String outstr = "这是写入文件的数据";
byte buf[] = outstr.getBytes();
fileout.write(buf);
fileout.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
文件的读出
try {
FileInputStream filein = new FileInputStream(f);
byte[] buf = new byte[1024];
String instr ="";
int length = filein.read(buf);
instr = new String(buf,0,length);
System.out.println(instr);
filein.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
将一个文件中的内容复制到文件2
public static void main(String[] args)
{
File f1 = new File("E:\\temp.txt");
File f2 = new File("E:\\temp2.txt");
FileInputStream fin = null;
FileOutputStream fout = null;
FileInputStream fin2 = null;
try {
fin = new FileInputStream(f1);
byte[] buf = new byte[10240];
int length = fin.read(buf);
String str = new String(buf,0,length);
System.out.println("文件1"+str);
System.out.println(fin.getFD());
try {
fout = new FileOutputStream(f2);
byte[] buf2 = str.getBytes();
fout.write(buf2, 0, length);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
fout.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
fin.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
try {
fin2 =new FileInputStream(f2);
byte[] buf3 = new byte[10240];
int length2 = fin2.read(buf3);
String str2 = new String(buf3,0,length2);
System.out.println("文件2"+str2);
System.out.println(fin2.getFD());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
fin2.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}