一、四種方式分別舉例
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());
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();
}
二、源碼:
- 歡迎關注微信公衆號:傅里葉變換,個人賬號,僅用於技術交流