对字符和字节的处理,在Java的I/O包里面有很好的处理类
1字节的处理
有FileOutputScream和FileInputScream两个常用类
FileInputScream构造方法常用两个,一个FileInputScream(File file)和FileInputScream(String name),FileOutputScream一样。
FileOutputScream对应的是将数据写入文件的输出流,常用方法有
(1)write()(将指定字节写入此文件输出流),
(2)write(byte[] b)( 将
b.length
个字节从指定 byte 数组写入此文件输出流中),
(3)write(byte[] b,int off,int len)( 将指定
byte 数组中从偏移量 off
开始的 len
个字节写入此文件输出流)
FileInputScream对应的是从系统中的某个文件获得它的里面的字节,常用方法有 (1)read()(从此输入流中读取一个数据字节),
(2)read(byte[] b)(从此输入流中将最多
b.length
个字节的数据读入一个 byte 数组中)
(3)read(byte[] b,int off,int len)(
从此输入流中将最多 len
个字节的数据读入一个 byte 数组中)
将字符串写入文件及输出的例子:
public static void main(String[] args) throws IOException {
String string = "Helloworld";//目标字符串
FileInputStream f1 = new FileInputStream("a.txt");
FileOutputStream f2 = new FileOutputStream("a.txt");
byte b[] = new byte[15];
byte b1[] = new byte[15];
b=string.getBytes();//将字符串转换成数组
f2.write(b);//将字节数组写入对应文件
f1.read(b1);//将文件里面内容读入数组
System.out.println(new String(b1));//将数组转换成字符串输出
}
2字符的处理常用类FileReader(用来读取字符文件的便捷类)和FileWriter(用来写入字符文件的便捷类)
FileReader构造方法:FileReader(String FileName),FileReader(FileReader,boolean append)(append
- 一个 boolean 值,如果为
true
,则将数据写入文件末尾处,如果不是写入文件开始处),FileReader(File file),FileReader(File file,boolean append)(append效果同上)
FileWriter构造方法类似
FileWriter常用方法:
(1)write(int c)(写入单个字符,参数c为指定要写入字符的 int)
(2)write(char[] c)(写入字符数组,c要写入的字符数组)
(3)write(char[] c,int off,int len)(写入字符数组的某一部分,c要写入的字符数组,off开始写入字符的位置,len要写入的长度)
(4)write(String str))(写入字符串,str为要写入的字符串)
(5)write(String str,int off,int len)(写入部分字符串,off开始写入字符的位置,len要写入的长度)
FileReader常用方法:
(1)read(读取单个字符)
(2)read(char c,int off,int len)(读取字符到数组的一部分)
(3)read(char c)(读取字符到数组)
同样例子代码:
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("b.txt");
FileWriter fileWriter = new FileWriter("b.txt");
String string = "LoopMIkoa";//目标字符串
char c[] = new char[15];
fileWriter.write(string);//进行数据的写入
fileWriter.close();//关闭FileWriter
fileReader.read(c);//将文件内容读进字符数组里面
System.out.println(new String(c));//构造方法把字符数组换成字符串
}