IO流
java中提供了专用于输入输出功能的包Java.io,其中包括:
InputStream,OutputStream,Reader,Writer
InputStream 和OutputStream,两个是为字节流设计的,主要用来处理字节或二进制对象,
Reader和 Writer.两个是为字符流(一个字符占两个字节)设计的,主要用来处理字符或字符串.
字节流可用于任何类型的对象,包括二进制对象,而字符流只能处理字符或者字符串; 2. 字节流提供了处理任何类型的IO操作的功能,但它不能直接处理Unicode字符,而字符流就可以
文件中换行为:\r\n
字节流(常用来处理二进制数据)
Java中的字节流处理的最基本单位为单个字节
读到内存:
InputStream in = new FileInputStream(输入内容及名字);
byte[] b = new byte[in.available()];//一种存储
in.read(b);
从内存写出:
OutputStream out = new FileOutputStream(输出路径及名字);
out.write(b);
字符流(常用来处理文本数据)
Java中的字符流处理的最基本的单元是Unicode码元(大小2字节)
读到内存:
Reader reader = new FileReader(输入内容及名字);
//reader.read(c);
StringBuffer sb = new StringBuffer();
while ((s = br.readLine())!=null){
sb.append(s+"\r\n");
}
String a = sb.toString();
从内存写出:
Writer writer = new FileWriter(输出路径及名字);
writer.write(a);
字节流案例:
public static void main(String[] args) {
InputStream in =null;
OutputStream out =null;
try {
//读到内存
in = new FileInputStream("D:\\autumn\\Desktop\\ioIn.txt");
byte[] b = new byte[in.available()];
in.read(b);
//System.out.println(new String(b));
//从内存写出
out = new FileOutputStream("D:\\autumn\\Desktop\\ioOut.txt");
out.write(b);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流案例:
public static void main(String[] args) {
BufferedReader br =null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("D:\\autumn\\Desktop\\ioIn.txt"));
bw = new BufferedWriter(new FileWriter("D:\\autumn\\Desktop\\ioOut.txt"));
String s = null;
StringBuffer sb = new StringBuffer();
while ((s = br.readLine())!=null){
sb.append(s+"\r\n");
}
System.out.println(sb);
bw.write(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Reader reader =null;
Writer writer = null;
try {
reader = new FileReader("D:\\autumn\\Desktop\\ioIn.txt");
writer = new FileWriter("D:\\autumn\\Desktop\\ioOut.txt");
char[] c = new char[10];
int i = 0;
StringBuffer sb = new StringBuffer();
while ((i=reader.read(c))!=-1){
sb.append(c,0,i);
}
String a = sb.toString();
writer.write(a);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}