关于I/O流中的write(int c)方法的解释
在API中对于字节流和字符流的这个方法,给出的介绍是:Writes the specified byte to this file output stream.即将特定的字符写入outputstream.这个特定的字符并非指的是读取的内容的某一特定位置的字符,而是ASCII码中某个数字所代指的那个字符正如此代码:
原始的HelloWorld.txt:
package Review;
import java.io.*;
public class IOTest {
public static void main(String[] args) {
try( FileReader read = new FileReader("C:\\Users\\Administrator.DESKTOP-GG79PJH\\Documents\\HellloWorld.txt");
FileWriter write = new FileWriter("C:\\Users\\Administrator.DESKTOP-GG79PJH\\Documents\\IOTest.txt");
) {
char[]buffer=new char[10];
int len=read.read(buffer);
while(len!=-1){
String copy = new String(buffer);
System.out.println(copy);
write.write(98);//******该处98在ASCII码中所代指的是小写的b
len=read.read(buffer);
}
write.close();
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
所以输出的是IOTest是:
相似的我们用字符流:
package Review;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOTestTwo {
public static void main(String[] args) {
try(FileInputStream in = new FileInputStream("C:\\Users\\Administrator.DESKTOP-GG79PJH\\Documents\\HellloWorld.txt");
FileOutputStream out = new FileOutputStream("C:\\Users\\Administrator.DESKTOP-GG79PJH\\Documents\\IOTestOne.txt");) {
byte[]buffer=new byte[10];
int len=in.read(buffer);
while(len!=-1){
String copy = new String(buffer);
System.out.println(copy);
out.write(65);
len=in.read(buffer);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我们得出的结果是:
那么为什么会输出的都是三个字符呢,这取决于这个源文件的长度,由于它的长度刚好执行三次就可以结束,如图:
此时如果我们修改一下源文件,加一个小数点,则会显示四个字符了,其实本质也就是将原本要输出的所有的字符串以一个单独的字符代替了。