IO装饰流之替换文本里的指定数据
定义两个文件:a.txt b.txt
a.txt存放A-Z的26个字母
从控制台输入要替换的字母 ,例如N
从控制台输入要替换的索引 例如:1
a.txt内容为:
ABCDEFGHIJKLMN…
b.txt内容为:
ANCDEFGHIJKLMN…
public class Work{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("请输入新字母:");
String s = sc.next();
char c = s.charAt(s.length() - 1);
System.out.print("请输入索引:");
int index = sc.nextInt();
StaticWork.work("a.txt","b.txt",c,index);
}
}
public class StaticWork{
public static void work(String str1,String str2,char c,int index){
try(//装饰基本流
BufferedInputStream stream01 = new BufferedInputStream(new FileInputStream(str1));
BufferedOutputStream stream02 = new BufferesOutputStream(new FileOutputStream(str2));
){
List<Character> list = new ArrayList<>();
int data = 0;
while((data = stream01.read()) != -1){
//byte强转为char
char ch = (char)data;
list.add(ch);
//替换元素
list.set(index,c);
}
StringBuilder builder = new StringBuilder();
String string = null;
for(char chars : list){
string = builder.append(chars).toString;
}
byte[] bytes = string.getBytes();
stream02.write(bytes);
}catch(Exception e){
e.printStackTrace();
}
}
}