用字節流一個字節一個字節的讀取一個文件
import java.io.*;
public class IOtest {
public static void main(String[] args) {
File file = new File("F:/ideawork/Threadstudy/IO/abc.txt");
InputStream is=null;
try{
is=new FileInputStream(file);
int temp;
while((temp=is.read())!=-1){
System.out.print((char)temp);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
加快效率 我們用字節流一段一段的讀取,在上面代碼做點改進即可
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class IOtest2 {
public static void main(String[] args) {
File file = new File("F:/ideawork/Threadstudy/IO/abc.txt");
InputStream is=null;
try{
is=new FileInputStream(file);
int len=-1;
//操作 分段讀取
byte[] bytes=new byte[3];//緩衝容器 每三個字節讀取一次
while((len=is.read(bytes))!=-1) {//接受長度
//字節數組到字符串 解碼
String s = new String(bytes, 0, len);
System.out.println(s);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
用字節流向文件中寫入內容
import java.io.*;
import java.util.stream.Stream;
public class IOtest3 {
public static void main(String[] args) {
File file = new File("F:/ideawork/Threadstudy/IO/desk.txt");
OutputStream os=null;
try{
os =new FileOutputStream(file);//覆蓋式寫入
//os =new FileOutputStream(file,true);//追加式寫入
String txt="aaaaaaaa";
byte[] datas =txt.getBytes();
os.write(datas,0,datas.length);
os.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
文件拷貝
我們只需要講上面的輸入輸出流連接到一起 就可以完成我們的文件拷貝操作
import java.io.*;
public class filetofile {
public static void main(String[] args) {
InputStream is=null;
OutputStream os=null;
try {
is=new FileInputStream("F:/ideawork/Threadstudy/IO/m.jpg");
os=new FileOutputStream("F:/ideawork/Threadstudy/IO/mcopy.jpg");
byte[] bytes = new byte[1024];
int len=-1;
while((len=is.read(bytes))!=-1){
os.write(bytes,0,len);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
//分別關閉 先打開的後關閉
try {
if(os!=null)
os.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if(is!=null)
is.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}