Java文件字節流

//輸出和輸入流java

package com.kangkang.IO;緩存

import com.sun.xml.internal.ws.util.xml.CDATA;code

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;xml

public class demo01 {
public static void main(String[] args) throws IOException {
//數據的寫入
byte[] data = {15,5,63,46};
File file = new File("example.123");
FileOutputStream outputStream = new FileOutputStream(file);字符串

outputStream.write(data,0,4);
    outputStream.close();
    System.out.println("Exit..");
}

}get

package com.kangkang.IO;input

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;it

public class demo02 {
public static void main(String[] args) throws IOException {
//數據的讀取io

//用於接收數據的緩衝區,須要足夠大
    byte[] buffer = new byte[50];
    // 能夠使用絕對路徑,如c:/加文件的目錄
    // 也能夠使用相對路徑,把文件放在項目目錄下
    File file = new File("kangkang.txt");
    // 從文件讀取數據,存放進緩存區
    FileInputStream inputStream = new FileInputStream(file);
    int n = inputStream.read(buffer,0,50);
    inputStream.close();
    System.out.println("獲取了"+n+"字節");
    System.out.println("Exit");
    String str = new String(buffer,0,n,"UTF-8");
    System.out.println(str);
}

}class

package com.kangkang.IO;

import java.io.File;
import java.io.FileOutputStream;

public class demo03 {
public static void main(String[] args) throws Exception{
//文件的寫入

//字符串
    String str = "康康你好帥";
    //由於文件裏面所有都是字節形式,因此要把字符串轉換爲字節才能寫入文件中
    byte[] data = str.getBytes("UTF-8");
    File file = new File("kang.999");
    FileOutputStream outputStream = new FileOutputStream(file);
    outputStream.write(data);

    outputStream.close();
    System.out.println("Exit");
}

}

package com.kangkang.IO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class demo04 {
public static void main(String[] args) throws Exception {
// 讀取文件的內容

byte[] buffer = new byte[100];
    File file = new File("kangkang.txt");
    FileInputStream inputStream = new FileInputStream(file);
    int n =inputStream.read(buffer,0,100);
    System.out.println("讀取了"+n+"字節");
    inputStream.close();
    // 寫入用什麼格式,解碼的時候也要用什麼格式
    String str = new String(buffer,0,n,"UTF-8");
    System.out.println(str);
    System.out.println("Exit");
}

}

相關文章
相關標籤/搜索