Java基础(3):文件输入输出

本文详细介绍了Java中文件的输入输出方式,包括字节流和字符流的使用方法及示例。

        Java文件的输入输出方式包括按字节流输入输出和按字符字符输入输出。

字节流

        字节流的输入包括:Inputstream,FileInputStream,BufferedInputStream,DataInputStream;输出包括:Outputstream,FileOutputStream,BufferedOutputStream,DataOutputStream

示例1:

public class FileIOTest {

@Test
public void test() throws IOException {

InputStream in = null;
OutputStream out= null;
try {
in=new FileInputStream("C:read.txt");
out=new FileOutputStream("C:write.txt");
byte []by=new byte[1024];
int ch;
while((ch=in.read(by))!=-1){
out.write(by);

out.flush();
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
in.close();
out.close();
}
}



}

示例2:

public class FileIOTest {

@Test
public void test() throws IOException {

BufferedInputStream in = null;
BufferedOutputStream out= null;
try {
in=new BufferedInputStream(new FileInputStream("C:read.txt"));
out=new BufferedOutputStream(new FileOutputStream("C:write.txt"));
byte []by=new byte[1024];
int ch;
while((ch=in.read(by))!=-1){
out.write(by);

out.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
in.close();
out.close();
}
}

}


BufferedInputStream和BufferedOutputStream都是将内容先放在缓冲区,然后进行处理,效率更高。

字符

       字符的输入包括:Reader,FileReader,BufferedReader;输出包括:Writer,FileWriter,BufferedWriter。

示例1:

public class FileIOTest {

@Test
public void test() throws IOException {

Reader in = null;
Writer out= null;
try {
in=new FileReader("C:read.txt");
out=new FileWriter("C:write.txt");
int line;
while((line=in.read())!=-1){
out.write((char)line);
System.out.println((char)line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
in.close();
out.close();
}
}

}


示例2:

public class FileIOTest {

@Test
public void test() throws IOException {

BufferedReader in = null;
BufferedWriter out= null;
try {
in=new BufferedReader(new FileReader("C:read.txt"));
out=new BufferedWriter(new FileWriter("C:write.txt"));
String line;
while((line=in.readLine())!=null){
out.write(line);
System.out.println(line);
}
//out.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
in.close();
out.close();
}
}

}




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值