使用字节流读写数据
使用字节流读文件
File file = new File("test.txt");
if (file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileInputStream fis = new FileInputStream("test.txt");//输入流
byte input[] = new byte[20];//创建字节数组存放读取的字节
fis.read(input);//读取字节
String inputString = new String(input,"gbk");//将读取的字节赋予字符串,并编码
System.out.println(inputString);//输出字符串
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
使用字节流写文件
FileOutputStream fos = new FileOutputStream(文件名);
String outString = “1233456567567”;
Byte output[] = outString.getBytes(“utf-8”);
Fos.write(output);
Fos.close();
带缓冲的字节流读写文件
try { FileInputStream fis = new FileInputStream("test.txt"); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream("new test.txt"); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] input = new byte[100]; while (bis.read(input) != -1){ bos.write(input); } bos.close(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
有缓冲流可以更快速的读写