一、四种方式分别举例
1.FileInputStream
InputStream is = null;
String address = "E:\\d05_gitcode\\Java\\newJava\\src\\com\\newJava\\newFile.txt";
int b;
try {
is = new FileInputStream(address);
while ((b = is.read()) != -1) { // 可以看出是一个字节一个字节读取的
System.out.println((char)b);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
可以看出字符是占用至少两个字节的,我们打出的都是一堆问号,这是只打印出了一个字节,而不是字符
2.FileOutputStream
FileOutputStream fis = null;
try {
fis = new FileOutputStream(address);
fis.write("有点优秀".getBytes()); // getBytes()获取这个字符串的byte数组,下面的toCharArray()获取字符数组
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
这里利用了字符串带有函数getBytes(),返回了一个Byte数组,传入这个字节数组,下面的FileWriter就是传入的char数组
3.FileReader
FileReader fr = null;
try {
fr = new FileReader(address);
while((b = fr.read()) != -1) {
System.out.println((char)b);
}
} catch (IOException e) {
e.printStackTrace();
}
这个就把字符给显示出来了
4.FileWriter
FileWriter fw = null;
char[] arargs = "太牛逼了".toCharArray();
try {
fw = new FileWriter(address);
fw.write(arargs, 0, arargs.length);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
5.ByteArrayInputStream
try {
byte[] arr = "厉害了".getBytes(StandardCharsets.UTF_8);
InputStream is2 = new BufferedInputStream(new ByteArrayInputStream(arr));
byte[] flush = new byte[1024];
int len = 0;
while((len = is2.read(flush)) != -1) {
System.out.println(new String(flush, 0, len));
}
} catch(Exception e) {
e.printStackTrace();
}
6.ByteArrayOutputStream
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] info = "厉害了".getBytes();
baos.write(info, 0, info.length);
byte[] dest = baos.toByteArray();
baos.close();
} catch(Exception e) {
e.printStackTrace();
}
二、源码:
github路径:https://github.com/ruigege66/Java/blob/master/newJava/src/com/newJava CSDN:https://blog.csdn.net/weixin_44630050 博客园:https://www.cnblogs.com/ruigege0000/ 欢迎关注微信公众号:傅里叶变换,个人账号,仅用于技术交流