Java专题十一(1):IO概述
目录
IO是基于字节流和字符流操作的
IO基类:
Reader | Writer | InputStream | OutputStream | |
---|---|---|---|---|
字符流 | ✔ | ✔ | ||
字节流 | ✔ | ✔ | ||
输入流 | ✔ | ✔ | ||
输出流 | ✔ | ✔ |
各种资源IO类:
Reader | Writer | InputStream | OutputStream | |
---|---|---|---|---|
File | FileReader | FileWriter | FileInputStream | FileOutputStream |
Buffer | BufferReader | BufferWriter | BufferedInputStream | BufferedOutputStream |
Pipe | PipedReader | PipedWriter | PipedInputStream | PipedOutputStream |
String | StringReader | StringWriter | ||
ByteArray | ByteArrayReader | ByteArrayWriter | ByteArrayInputStream | ByteArrayOutputStream |
CharArray | CharArrayReader | CharArrayWriter | ||
Object | ObjectInputStream | ObjectOutputStream | ||
Filter | FilterReader | FilterWriter | FilterInputStream | FilterOutputStream |
Data | DataInputStream | DataOutputStream |
1.字节流转换成字符(InputStreamReader)
public static String byte2Char(InputStream is, String charsetName)
throws IOException {
if (charsetName == null || !Charset.isSupported(charsetName)){
charsetName = DEFAULT_CHARSET;
}
InputStreamReader isr = new InputStreamReader(is, charsetName);
char[] cbuf = new char[DEFAULT_BYTE_SIZE];
StringBuilder sbf = new StringBuilder();
int readCount;
while((readCount = isr.read(cbuf)) > 0){
sbf.append(cbuf, 0, readCount);
}
return sbf.toString();
}
2.从文件中读取字符(FileReader)
public static String readCharFromFile(String path) throws IOException {
File fi = new File(path);
if (fi.exists() && fi.isFile()){
FileReader fr = new FileReader(fi);
char[] cbuf = new char[DEFAULT_CHAR_SIZE];
int readCount;
StringBuilder sbf = new StringBuilder();
while((readCount = fr.read(cbuf)) > 0){
sbf.append(cbuf, 0, readCount);
}
return sbf.toString();
}
throw new FileNotFoundException();
}
3.字节流输出到文件(FileOutputStream)
public static File writeByteToFile(InputStream is, String path, boolean append) throws IOException {
File fi = new File(path);
// create file first if not exists
if (!fi.exists()) {
fi.createNewFile();
append = false;
}
FileOutputStream fos = new FileOutputStream(fi, append);
byte[] buf = new byte[DEFAULT_BYTE_SIZE];
int readCount;
while((readCount = is.read(buf)) > 0){
fos.write(buf, 0, readCount);
}
fos.close();
is.close();
return fi;
}
4.字符输出到文件(FileWriter)
public static File writeCharToFile(String content, String path, boolean append) throws IOException {
File fi = new File(path);
// create file first if not exists
if (!fi.exists()) {
fi.createNewFile();
append = false;
}
FileWriter fw = new FileWriter(fi, append);
fw.write(content, 0, content.length());
fw.close();
return fi;
}
字节流转换成字符流,文件与字节,文件与字符转换操作完整代码见:
IOTools