package fengke.byteandchar; |
import java.io.File; |
import java.io.FileOutputStream; |
import java.io.OutputStream; |
/** |
* 字節流 |
* @author 锋客 |
* 没有关闭字节流操作,但是文件中也依然存在了输出的内容,证明字节流是直接操作文件本身的 |
*/ |
public class ByteDemo { |
public static void main(String[] args) throws Exception { // 异常抛出, 不处理 |
// 第1步:使用File类找到一个文件 |
File f = new File( "e:" + File.separator + "test.txt" ); // 声明File 对象 |
// 第2步:通过子类实例化父类对象 |
OutputStream out = null ; |
// 准备好一个输出的对象 |
out = new FileOutputStream(f); |
// 通过对象多态性进行实例化 |
// 第3步:进行写操作 |
String str = "鋒客測試" ; |
// 准备一个字符串 |
byte b[] = str.getBytes(); |
// 字符串转byte数组 |
out.write(b); |
// 将内容输出 |
// 第4步:关闭输出流 |
// out.close(); |
// 此时没有关闭 但任然可以看到文件中有Hello World!!! |
} |
} |
package fengke.byteandchar; |
import java.io.File; |
import java.io.FileWriter; |
import java.io.Writer; |
/** |
* 字符流 |
* @author 锋客 |
* 程序运行后会发现文件中没有任何内容,这是因为字符流操作时使用了缓冲区,而 |
* 在关闭字符流时会强制性地将缓冲区中的内容进行输出,但是如果程序没有关闭,则缓冲区中的内容是无法输出的, |
*/ |
public class CharDemo { |
public static void main(String[] args) throws Exception { // 异常抛出, 不处理 |
// 第1步:使用File类找到一个文件 |
File f = new File( "e:" + File.separator + "test1.txt" ); // 声明File 对象 |
// 第2步:通过子类实例化父类对象 |
Writer out = null ; |
// 准备好一个输出的对象 |
out = new FileWriter(f); |
// 通过对象多态性进行实例化 |
// 第3步:进行写操作 |
String str = "Hello World!!!" ; |
// 准备一个字符串 |
out.write(str); |
// 将内容输出 |
// 第4步:关闭输出流 |
// out.close(); |
// 此时没有关闭 |
} |
} |