java中字节级数据文件的读写编程

Python013

java中字节级数据文件的读写编程,第1张

import java.util.Scanner

import java.io.*

class MyFile

{

MyFile(String d)

{

this.d=d

}

void write(String path,String datafile)

{

File f=new File(this.d)

StringBuilder sb=new StringBuilder()

String savepath

String[] strs

BufferedOutputStream bos

byte[] buf

this.path=path.endsWith("\\") ? path.substring(0,path.length()-1) : path

savepath=this.path+"\\"+datafile

try

{

strs=f.list()

for(String str : strs)

{

sb.append(str)

sb.append("\r\n")

}

bos=new BufferedOutputStream(new FileOutputStream(savepath),MyFile.Size)

buf=sb.toString().getBytes()

bos.write(buf,0,buf.length)

//bos.flush()

bos.close()

}

catch(Exception e)

{

System.out.println(e.getMessage())

}

}

void show(String datafile)

{

String fp=datafile.contains("\\") ? datafile : this.path+"\\"+datafile

File f=new File(fp)

BufferedInputStream bis

byte[] buf

try

{

buf=new byte[(int)f.length()]

bis=new BufferedInputStream(new FileInputStream(f),MyFile.Size)

bis.read(buf,0,buf.length)

System.out.println(new String(buf))

bis.close()

}

catch(Exception e)

{

System.out.println(e.getMessage())

}

}

private static final int Size=8*1024

private String d,path

}

public class P

{

public static void main(String[] args)

{

Scanner sc=new Scanner(System.in)

MyFile f

String d,path,datafile

System.out.print("请输入windows系统中某个目录的路径:")

d=sc.nextLine()

f=new MyFile(d)

System.out.print("请输入保存数据的文件的路径:")

path=sc.nextLine()

System.out.print("请输入保存数据的文件的文件名:")

datafile=sc.nextLine()

f.write(path,datafile)

f.show(datafile)

sc.close()

}

}

分为读字节,读字符两种读法\x0d\x0a◎◎◎FileInputStream 字节输入流读文件◎◎◎\x0d\x0apublic class Maintest {\x0d\x0a\x0d\x0apublic static void main(String[] args) throws IOException {\x0d\x0a\x0d\x0aFile f=new File("G:\\just for fun\\xiangwei.txt")\x0d\x0a\x0d\x0aFileInputStream fin=new FileInputStream(f)\x0d\x0a\x0d\x0abyte[] bs=new byte[1024]\x0d\x0a\x0d\x0aint count=0\x0d\x0awhile((count=fin.read(bs))>0)\x0d\x0a{\x0d\x0a\x0d\x0aString str=new String(bs,0,count)//反复定义新变量:每一次都 重新定义新变量,接收新读取的数据\x0d\x0a\x0d\x0aSystem.out.println(str)//反复输出新变量:每一次都 输出重新定义的新变量\x0d\x0a}\x0d\x0afin.close()\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0a◎◎◎FileReader 字符输入流读文件◎◎◎\x0d\x0apublic class Maintest {\x0d\x0apublic static void main(String[] args) throws IOException {\x0d\x0a\x0d\x0aFile f=new File("H:\\just for fun\\xiangwei.txt")\x0d\x0a\x0d\x0aFileReader fre=new FileReader(f)\x0d\x0a\x0d\x0aBufferedReader bre=new BufferedReader(fre)\x0d\x0a\x0d\x0aString str=""\x0d\x0awhile((str=bre.readLine())!=null)//●判断最后一行不存在,为空\x0d\x0a{\x0d\x0aSystem.out.println(str)\x0d\x0a}\x0d\x0abre.close()\x0d\x0a fre.close()\x0d\x0a\x0d\x0a}\x0d\x0a\x0d\x0a}