java 中文件写入读出

对文件的操作可以利用 File 类进行操作。
1字节=8位
file.length() 返回的是字节 byte
工具类一般要用静态方法。
读取文件函数
public static String readFile(String filename) throws IOException{
String content="";
File file=new File(filename);
InputStream inputStream=new FileInputStream(file);//向上转型 字节-》字节流
//从流中取得数据
int length=(int) file.length();//的到文件长度
// for(int i=0;i<length;i++){ //第一种读取方法--效率低,频繁与硬盘交流
// int data=inputStream.read();
// content+=(char)data;
// System.out.println((char)data);
// }
byte[] b=new byte[length];//第二中读取方法
inputStream.read(b);
content=new String(b,"utf-8");//可以通过String构造函数进行对字节的处理,后面指定编码规则
inputStream.close();
return content;
}
写入文件函数
public static void writeFile(String content,String filename) throws IOException{
File file=new File(filename);
OutputStream outputstream=new FileOutputStream(file,true);//后面加个true将为一个追加模式;
byte[] b=content.getBytes("utf-8");//指定编码格式
outputstream.write(b);
outputstream.close();
}
缓冲流(减少对硬盘的访问,就是从硬盘读取后放在缓冲流,然后重缓冲流进行操作)
程序操作:
InputStream inputstream;
BufferedInputStream buffer=new BufferInputStream(inputStream);
buffer.read(b);

OutputStream outputstream;
BufferedOutputStream buffer=new BufferOutputStream(outputStream);
buffer.write(b);
关闭的时候先关闭缓冲流后再关闭输入流
字符流
(最大好处就是不用关心字符的编码问题)
读出数据:
public static String readFileByCharacterStream(String filename) throws IOException{
String connent=" ";
File file=new File(filename);
Reader reader=new FileReader(file);
int length=(int) file.length();
char [] charArray=new char[length];
reader.read(charArray);
reader.close();
connent=new String(charArray);
return connent;
}
使用缓冲流读出数据
public static String readFileByCharacterStreamUsingBufferStream(String filename) throws IOException{
String connent=" ";
File file=new File(filename);
Reader reader=new FileReader(file);
BufferedReader bufferreader=new BufferedReader(reader);
StringBuilder build=new StringBuilder();//不可以在有多线程的地方使用,在多线程用StringBuffer
String line=bufferreader.readLine();
while(line!=null){
build.append(line);
line=bufferreader.readLine();
}
bufferreader.close();
reader.close();
connent=build.toString();
return connent;
}
使用缓冲流写入数据
public static void WriteFileByCharacterString(String connent,String descFile) throws IOException{
File file=new File(descFile);
Writer write=new FileWriter(descFile,true);
BufferedWriter bufferwriter=new BufferedWriter(write);
bufferwriter.write(connent);
bufferwriter.close();
write.close();
}

读写文件的基本步骤

字节流
File->InputStream(FileInputStream) || OutputStream(FileOutputStream)->BufferedInputStream|| BufferedOutputStream

字符流
File->Reader(FileReader) || Writer(FileWriter) ->BufferedReader || BufferedWriter

记得要按栈的方式 先开后关来 关闭这些流!!!!!!!!!!!!!!!




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值