// FileOutputStream 文件字节流输出
public void FileOutputStreamTest1() throws IOException {
// 1.使用File找到一个文件
File file = new File("f:" + File.separator + "cnn.txt");
// 2.通过子类实例化父类对象
OutputStream out = null;
out = new FileOutputStream(file); //
// 3.进行读写
String str = "Hello World!";
byte[] bt = str.getBytes();// 只能輸出字节数组
out.write(bt);
// 关闭输出流
out.close();
}
// FileOutputStream 文件字节流输出
public void FileOutputStreamTest2() throws IOException {
// 1.使用File找到一个文件
File file = new File("f:" + File.separator + "cnn.txt");
// 2.通过子类实例化父类对象
OutputStream out = null;
out = new FileOutputStream(file);
// 3.进行读写
String str = "Hello World!";
byte[] bt = str.getBytes();// 只能輸出字节数组
for (int i = 0; i < bt.length; i++) {
out.write(bt[i]);
}
// 关闭输出流
out.close();
}
//FileInputStream 文件字节输入流
public void FileInputStreamDemo1() throws IOException {
// 1使用File类找到文件
File f = new File("f:" + File.separator + "cnn.txt");
// 2.通过子类实例化父类对象
InputStream in = null;// 准备好一个输入的对象
in = new FileInputStream(f);
// 3.进行读写
byte[] bt = new byte[1024];
int len = 0;
int temp = 0;
while ((temp = in.read()) != -1) {
bt[len] = (byte) temp;
len++;
}
// 4.关闭输入流
in.close();
}
// 字节流转化为字符流
public void OutputStreamWriterDemo1() throws IOException {
File f = new File("f:" + File.separator + "cnn.txt");
Writer out = null;
out = new OutputStreamWriter(new FileOutputStream(f));
out.write("Hello World");
out.close();
}
public void InputStreamReaderDemo1() throws IOException {
File f = new File("f:" + File.separator + "cnn.txt");
Reader in = null;
in = new InputStreamReader(new FileInputStream(f));
char[] c = new char[1024];
int len = in.read(c);// 读取
in.close(); // 关闭
}
// 内存流读写
public void ByteArraryDemo() throws IOException {
String str = "HELLOWORLD!";
ByteArrayInputStream bis = null;// 內存輸入流
ByteArrayOutputStream bos = null;// 內存輸出流
bis = new ByteArrayInputStream(str.getBytes()); // 向内存中输入内容
bos = new ByteArrayOutputStream(); // 准备从ByteArrayInputStream读取内容
int temp = 0;
while ((temp = bis.read()) != -1) {
char c = (char) temp; // 读取数字变成字符
bos.write(Character.toLowerCase(c)); // 轉換小寫
}
bis.close();
bos.close();
String newStr = bos.toString();
System.out.println(newStr);
}
// BufferedReader 从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取
public void BufferedReaderDemo() throws IOException {
BufferedReader bf = null; // 声明BufferedReader对象
// 1.System.in 字節輸入流
// 2.new InputStreamReader(System.in) 将字节输入流,转换为字符输入流
// 3.new BufferedReader(new InputStreamReader(System.in)) 将字符流缓冲到缓冲区
bf = new BufferedReader(new InputStreamReader(System.in));
String str = null;
System.out.println("请输入内容:");
str = bf.readLine();
System.out.println("輸入的內容是:" + str);
}
FileOutputStream : out(byte[])和out(int)方法。
原文:http://my.oschina.net/u/263874/blog/375415