面试题:将一个文件的每一行末尾添加"*"后写入另一个文件
public static void main(String[] args) {
readAddWrite();
}
public static void readAddWrite(){
InputStream is =null;
OutputStream os=null;
try {
//创建输入输出流
is = new BufferedInputStream(new FileInputStream(new File("D:\\test\\s.txt")));
os = new BufferedOutputStream(new FileOutputStream(new File("D:\\test\\c.txt")));
int b;
//定义一个数组用于存储读取流的数据
byte[] buf = new byte[8192];
//定义一个数组用于存储要写出的数据
byte[] cs;
//将读取流的数据长度赋值给b并判断
while ((b=is.read(buf))!=-1){
//定义两个buf数组索引的指针,j为头,i为尾
int i = 0;
int j = 0;
//当i=b时buf中的数据全部读取完
while (i<b) {
//当buf数组中13和10连续出现代表回车换行
while (buf[i] == 13 && buf[i + 1] == 10) {
//将回车换行前的数据用bs存储起来
byte[] bs = Arrays.copyOfRange(buf, j, i);
//bs是满的,无法添加数据,所以对其扩容
cs = Arrays.copyOf(bs, 8192);
//i-j为cs数组中最后一个有效数据的后一位,写入*
cs[i-j] = 42;
//将回车换行前的数据和*直接写出
os.write(cs,0,i-j+1);
//将之前的头指针指向现在的尾指针
j = i;
//当没找到回车换行时尾指针只用向后移一位,当找到回车换行时,尾指针向后移两位
i ++;
}
i++;
}
//最后一行没有回车换行,直接取出数据在后面加上*并写出
byte[] bs = Arrays.copyOfRange(buf,j,b);
cs = Arrays.copyOf(bs, 8192);
cs[i-j] = 42;
os.write(cs,0 ,i+1 );
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
os = null;
is=null;
}
}
}