字节输入流
package com.fs.test;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
public class Test {
public void m1() throws Exception {
InputStream in= new FileInputStream("D:/test/b.txt");
byte[] buf = new byte[10];
in.read(buf);
String str = new String(buf);
System.out.println(str);
in.close();
}
public void m2() throws Exception {
InputStream in = new FileInputStream("d:/test/b.txt");
BufferedInputStream bin = new BufferedInputStream(in);
byte[] buf = new byte[10];
String str = "";
while(bin.read(buf) != -1){
str += new String(buf);
}
System.out.println(str);
bin.close();
in.close();
}
public static void main(String[] args) throws Exception {
Test t = new Test();
t.m1();
t.m2();
}
}
字节输出流
package com.fs.test;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Test {
public void m1() throws Exception {
OutputStream out = new FileOutputStream("d:/test/a.txt", true);
String str = "这是要输出的数据";
out.write(str.getBytes());
out.flush();
out.close();
}
public void m2() throws Exception {
OutputStream out = new FileOutputStream("d:/test/a.txt", true);
BufferedOutputStream bout = new BufferedOutputStream(out);
String str = "abcdefg";
byte[] buf = str.getBytes();
for(int i = 0; i < buf.length;i++){
Thread.sleep(1000);
bout.write(buf[i]);
}
bout.flush();
bout.close();
out.close();
}
public static void main(String[] args) throws Exception {
new Test().m2();
}
}
文件的复制
package com.fs.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
public class CopyFiles {
static String path = "c:/picture.PNG";
static String newpath = "d:/copy.PNG";
public static void main(String[] args) throws Exception {
File source = new File(path);
File dest = new File(newpath);
long start = 0;
long end = 0;
start = System.currentTimeMillis();
copy_FileChannel(source, dest);
end = System.currentTimeMillis();
System.out.println("copy_fileChannel" + (end - start));
}
public static void copy_FileChannel(File source, File dest) throws Exception {
@SuppressWarnings("resource")
FileChannel in = new FileInputStream(source).getChannel();
@SuppressWarnings("resource")
FileChannel out = new FileOutputStream(dest).getChannel();
out.transferFrom(in, 0, in.size());
in.close();
out.close();
}
public static void copy_File(File source, File dest) throws Exception {
Files.copy(source.toPath(), dest.toPath());
}
}