Java--字节文件和字符文件处理

字节流文件

  1. FileInputstream字节输入流 文件–>程序(读取字节流文件) 直接通过 read() 方法返回int类型数据,然后强制转换为char类型数据进行输出。(效率慢,不推荐) 通过byte数据先开辟数组,然后通过read(byte[])方法返回数组长度,最后通过创建字符串来进行拼接形成字符串。 System.out.print(new String(buf,0,readLen)); 最后记得关闭字节流 注意尽量不要对汉字进行操作。 @Test public void File01() { String filename = "d:\hello.txt";//获取文件地址 int readFile = 0; FileInputStream file = null; try { //获取文件 file = new FileInputStream(filename); //file.read()读出来返回的是int类型的数据,通过while循环不断地获取返回值的数据,知道为-1为止 while ((readFile = file.read()) != -1){ System.out.print((char) readFile); } } catch (IOException e) { e.printStackTrace(); }finally { try { file.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test public void File02(){ String fileName = "d:\hello.txt"; int readLen = 0; byte[] buf = new byte[8];//每次获取8个字节的数据 FileInputStream file = null; try { file = new FileInputStream(fileName); //通过数值获取字节 while((readLen = file.read(buf)) != -1){ //通过new重新组建字符串 System.out.print(new String(buf,0,readLen)); } } catch (IOException e) { e.printStackTrace(); }finally { try { file.close(); } catch (IOException e) { e.printStackTrace(); } } }
  2. FileOutPutStream 字节输出流 程序到文件(没有对应文件名可以自动创建)
@Test
   public void Output(){
          
   
       String filePath = "d:\a.txt";
       FileOutputStream file = null;

       try {
          
   
           //打开文件
           file = new FileOutputStream(filePath);
           //带true表示在文件后面追加字符 而不是直接覆盖
          // file = new FileOutputStream(filePath,true);
           //写入单个字节
           //file.write(h);
           String a="hello,world!";
           //通过getBytes() 直接传唤为数组状态写入
           file.write(a.getBytes());

           file.write(a.getBytes(),0,3);

       } catch (IOException e) {
          
   
           e.printStackTrace();
       } finally {
          
   
           try {
          
   
               file.close();
           } catch (IOException e) {
          
   
               e.printStackTrace();
           }
       }
   }
    关闭字节流
  1. 通过字节输入流和输出流混合运用可以实现数据的拷贝。即一边读取数据一边存取数据。存取数据时候用第三种方式进行存取。

字符文件处理

  1. FileReader 同字节流输入类似
  2. FileWriter 五种方式写入 fileWriter.write(‘H’); fileWriter.write(chars); //可以通过String.toCharArray()写入 fileWriter.write(chars,off,len); fileWriter.write(String) fileWriter.write(String,off,len) 一定要记得关流,否则写不进去 fileWriter.flush() fileWriter.close()
经验分享 程序员 微信小程序 职场和发展