1、字节流
使用字节缓冲区
- 将数据写到TXT中
public void IOTest() throws IOException
{
String str = "你好,世界";
FileOutputStream fos = new FileOutputStream("d:" + File.separator + "test.txt");
fos.write(str.getBytes("UTF-8")); //将字符串变成字节byte数组,使用UTF-8编码
fos.close();
}
- 将TXT导入到内存
FileInputStream fis = new FileInputStream("d:" + File.separator + "test.txt");
byte[] buf = new byte[1024];
int len; //用于记录读取的数据个数
String myStr = "";
while((len = fis.read(buf)) != -1) //将内容读到byte数组中,同时返回个数,若为-1,则内容读到底
{
myStr += new String(buf, 0, len, "UTF-8");
}
2、字符流
使用字节缓冲区
- 将数据写到TXT中
FileWriter fw = new FileWriter("d:" + File.separator + "test.txt");
fw.write(str);
fw.close();
- 将TXT导入内存中
FileReader fr = new FileReader("d:" + File.separator + "test.txt");
char[] buf2 = new char[1024];
int len2 = fr.read(buf2); //用于记录读取的数据个数
String myStr2 = new String(buf2, 0, len2); //将缓冲区buf2数组中的0到len2字符串读出
System.out.println(myStr2);
不使用字符缓冲区
不使用字节缓冲区
- 将数据写到TXT中
PrintWriter pw = new PrintWriter("d:" + File.separator + "test.txt", "UTF-8");
pw.write(str);
pw.close();
- 将TXT导入内存中
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("d:" + File.separator + "test.txt"), "UTF-8"));
String myStr3 = br.readLine();
br.close();
System.out.println(myStr3);