java 读写文件的代码。
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
-
- public class T1116 {
- static String str = "生活本就是见招拆招,不必过分焦虑。";
- final static String FILE = "d:\\test.txt";
-
- static void fun1() throws IOException {
- File file = new File(FILE);
- FileOutputStream fos = new FileOutputStream(file);
- OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
- osw.write(str);
- osw.close();
- fos.close();
- }
-
- static void fun2() throws IOException {
- File file = new File(FILE);
- FileInputStream fis = new FileInputStream(file);
- InputStreamReader isr = new InputStreamReader(fis, "utf-8");
-
- int c = 0;
- System.out.println("内容:");
- while ((c = isr.read()) != -1)
- System.out.print((char) c);
- System.out.println();
- isr.close();
- fis.close();
-
- }
-
- // 利用缓冲流复制test.txt为my.txt。
- static void fun3() throws IOException {
- // 读文件
- File file = new File(FILE);
- File file1 = new File("my.txt");
- FileInputStream fis = new FileInputStream(file);
- InputStreamReader isr = new InputStreamReader(fis, "utf-8");
- BufferedReader br = new BufferedReader(isr);
-
- FileOutputStream fos = new FileOutputStream(file1);
- OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
- BufferedWriter bw = new BufferedWriter(osw);
-
- String line;
-
- while ((line = br.readLine()) != null) {
- bw.write(line);
- }
- bw.close();
- osw.close();
- fos.close();
- br.close();
- isr.close();
- fis.close();
- System.out.println("my.txt的位置是:" + System.getProperty("user.dir"));
- }
-
- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- fun1();
- fun2();
- fun3();
-
- }
-
- }