Java IO 实现简单文件读与写

      使用Java IO 实现简单文件读与写

       package com.cn.test;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class FileTest {
//定义一个文件对象,指定要对哪一个文件要进行文件操作
    static File path=new File("F:\\file\\test.txt");
/**
* @param args
* @throws IOException 
* @throws UnsupportedEncodingException 
*/
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
OutStream();
InStram();
InStreamReader();

}

      //使用字符流来输出获取的文件信息

public static void InStreamReader() throws IOException
{
//定义一个输入流用来获取指定文件中内容
try {
FileInputStream fis=new FileInputStream(path);
//把字节流转换为字符流,字符编码为utf-8
InputStreamReader isr=new InputStreamReader(fis,"utf-8");
//把字符流放入到缓存流中
BufferedReader br=new BufferedReader(isr);
//读取缓存流中字符
String myStr=br.readLine();
System.out.println("读取的字符:"+myStr);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//使用字节流输入读取文件中信息
public static void InStram() throws IOException
{
try {
//定义一个输入流用来获取指定文件中内容
FileInputStream fis=new FileInputStream(path);
byte[] b=new byte[1024];
int len=0;
while((len=fis.read())>0)
{
fis.read(b, 0, len);
String str=new String(b, 0, len);
System.out.println(new String(str.getBytes(),"utf-8"));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//输出流方法
public static void OutStream() throws UnsupportedEncodingException, IOException
{
String msg="这是使用字节输入流的方式输入到此txt文件中的";
try {
//定义一个输出流对象来输出到指定文件中
FileOutputStream fos=new FileOutputStream(path);
//写入到指定的文件中
fos.write(msg.getBytes("utf-8"));
//关闭输出流
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值