逍遥子

java中对文件的读写操作
文件读取代码如下:package priess; import java.io.BufferedReader; ...
扫描右侧二维码阅读全文
10
2018/07

java中对文件的读写操作

文件读取

代码如下:

package priess;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class Mytxt {

    public static String txt2String(File file){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法,一次读一行
                result.append(System.lineSeparator()+s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }
    
    public static void main(String[] args){
        File file = new File("D:/errlog.txt");
        System.out.println(txt2String(file));
    }

}

文件写操作

代码:

package priess;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class MYtxtxie {
    static String b="hello world";
    static int a=123;
    public static void main(String args[]){
        contentToTxt("D:\\java.txt",a+b);
    }
    public static void contentToTxt(String filePath, String content) {
        try{
            BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath),true));
            writer.write("\n"+content);
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}
Last modification:July 10th, 2018 at 03:13 pm
正在沿街乞讨中……

Leave a Comment