本文 转自 中文JAVA技术网 » 墨羽翔天 » 博客 http://www.cn-java.com/www1/?uid-553689-action-viewspace-itemid-5128
写文件
package com.demo;
import java.io.*;
public class write {
public static void main(String[] args) {
write("D://workspace//javademo//13.txt", "hello");
}
public static void write(String path, String content) {
String s = new String();
String s1 = new String();
try {
File f = new File(path);
if (f.exists()) {
System.out.println("文件存在");
} else {
System.out.println("文件不存在,正在创建...");
if (f.createNewFile()) {
System.out.println("文件创建成功!");
} else {
System.out.println("文件创建失败!");
}
}
BufferedReader input = new BufferedReader(new FileReader(f));
while ((s = input.readLine()) != null) {
s1 += s + "/n";
}
System.out.println("文件内容:" + s1);
input.close();
s1 += content;
BufferedWriter utput = new BufferedWriter(new FileWriter(f));
utput.write(s1);
utput.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
读文件
package com.demo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
public class reader{
/**
* @param args
*/
public static void main(String[] args) {
read("D://workspace//javademo//13.txt");
}
public static void read(String file) {
String s = null;
StringBuffer sb = new StringBuffer();
File f = new File(file);
if (f.exists()) {
System.out.println("文件存在");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(f)));
while ((s = br.readLine()) != null) {
sb.append(s);
}
System.out.println(sb);
} catch (Exception e) {
e.printStackTrace();
}
}else{
System.out.println("文件不存在!");
}
}
}