InputStream?
package java_IO;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Test_FileInputStream {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//不能避免汉字出现乱码的问题;
//创建文件字节输入流管道、与源文件接通;
InputStream is = new FileInputStream(("src\\111.txt"));
//开始读取文件的字节数据;
//public int read();每次读取一个字节返回,如果没有数据了,返回-1;
// int b1 = is.read();
// System.out.println((char)b1);
// int b2 = is.read();
// System.out.println((char)b2);
// int b3 = is.read();
// System.out.println(b3);
int b;
while((b=is.read())!=-1) {
System.out.print((char)b);
}
is.close();
System.out.println();
System.out.println("-------每次读取多个字节------");
//创建一个字节输入流对象代表字节输入管道与源文件接通;
InputStream in = new FileInputStream(("src\\111.txt"));
//2.开始读取文件中的字节数据,每次读取多个字节;
byte[] buffer = new byte[3];
int len = in.read(buffer);
//读多少,倒多少;
String rs = new String(buffer,0,len);
System.out.println(rs);
System.out.println("当次读取的字节数量:"+len);
//buffer
int len2 = in.read(buffer);
//读多少,倒多少;
String rs2 = new String(buffer,0,len2);
System.out.println(rs2);
System.out.println("当次读取的字节数量:"+len2);
in.close();
}
}
package java_IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Test_FileInputStream1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//1.创建一个字节输入流管道与源文件接通;
InputStream is = new FileInputStream("src\\222.txt");
//2.准备一个字节数组,大小与文件的大小正好一样大;
File f = new File("src\\222.txt");
long size = f.length();
byte[] buffer = new byte[(int)size];
int len = is.read(buffer);
System.out.println(new String(buffer));
System.out.println(size);
System.out.println(len);
is.close();
}
}
OutputStream
package java_IO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Test_FileOutputStream {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//会覆盖之前的数据;
OutputStream os = new FileOutputStream("src\\444.txt");
byte[] bytes = "我爱你中国123abs".getBytes();
os.write(bytes);
os.write(bytes, 0, 15);
os.close();
//不会覆盖
OutputStream os1 = new FileOutputStream("src\\555.txt",true);
os1.write(bytes);
os1.write(bytes, 0, 15);
//换行
os1.write("\r\n".getBytes());
os1.close();
}
}
?
?