标签:
写入:
追加内容:
public static void main(String[] args) throws Exception { String data = " This content will append to the end of the file\n"; File file = new File("javaio-appendfile.txt"); if (!file.exists()) { file.createNewFile(); } FileWriter fileWritter = new FileWriter(file.getName(), true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(data); bufferWritter.close(); System.out.println("Done"); }
不追加的话 写成:
FileWriter fileWritter = new FileWriter(file.getName());
读取:
public static void ss() throws Exception{ String filePath = "C:\\Users\\acer\\Desktop\\111.txt"; StringBuilder sb = new StringBuilder(); String re = ""; String encoding="gbk"; File file=new File(filePath); if(file.isFile() && file.exists()){ //判断文件是否存在 InputStreamReader read = new InputStreamReader( new FileInputStream(file),encoding);//考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; int i = 0; while((lineTxt = bufferedReader.readLine()) != null){ lineTxt = lineTxt.trim(); sb.append(lineTxt); i++; } re = sb.toString(); System.out.println(re.length()); read.close(); } }
标签:
原文地址:http://www.cnblogs.com/lishupeng/p/5641920.html