您的位置:首页 > 其它

(字节流、字符流)对文件进行读写操作

2017-03-25 00:51 309 查看
/*

* 使用字符流对文件进行读写操作

*/

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.InputStreamReader;

import java.io.PrintWriter;

public class T04 {

public static void main(String[] args) throws Exception{

String value = “中国风\n”;

String value2 = “a 中国风\n”;

// 向文件中写入内容

PrintWriter pw = new PrintWriter(“temp.txt”,”UTF-8”);

pw.write(value);

pw.write(value2);

pw.close();

// 从文件中读取内容

BufferedReader br = new BufferedReader(new InputStreamReader(

new FileInputStream(“temp.txt”),”utf-8”));

String b;

while((b = br.readLine())!=null){ // 按行读取

System.out.println(b);

}

br.close();

}

}

运行结果:

中国风

a 中国风

/*

* 使用字节流对文件进行读写操作

*/

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.File;

public class T05 {

public static void main(String[] args) throws Exception{

String value = “中国风\n”;

String value2 = “a 中国风\n”;

// 向文件中写入内容

File f = new File(“temp.txt”);

FileOutputStream fos = new FileOutputStream(f);

fos.write(value.getBytes(“UTF-8”)); // 可以指定编码

fos.write(value2.getBytes());

fos.close();

// 从文件中读取内容

FileInputStream fis = new FileInputStream(f);

byte b[] = new byte[(int)f.length()];

int len = fis.read(b); // 读取后返回长度

fis.close();

System.out.println(new String(b));

}

}

运行结果:

涓浗椋�

a 中国风
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: