一、四種方式分別舉例
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/ 歡迎關注微信公眾號:傅里葉變換,個人賬號,僅用于技術交流 
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390256.html
標籤:其他
上一篇:1.8 字典的運算
