Java連載155-IO總結(二)

一、四種方式分別舉例

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();
   }
  }

155.1
155.1
  • 可以看出字符是佔用至少兩個字節的,我們打出的都是一堆問號,這是隻打印出了一個字節,而不是字符

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數組 155.2

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();
  }

155.3
155.3
  • 這個就把字符給顯示出來了

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();
  }
155.4
155.4

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();
  }

二、源碼:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章