public class ReadAndWriteToFile {
//将字符串写入文件
public static void writeFile(String s) throws IOException {
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("wdsin.txt")));
bw.write(s);
bw.close();
}
//读取文件内容
public static String readFile(String fileName) throws IOException {
File myFile=new File(fileName);
if (!myFile.exists()) {
System.err.println(fileName+"不存在!");
}
BufferedReader br=new BufferedReader(new FileReader(fileName));
String s;
while((s=br.readLine())!=null){
System.out.println(s);
}
br.close();
return s;
}
public static void main(String[] args) throws IOException {
String fileName="wdsin.txt";
writeFile(fileName);
readFile(fileName);
}
}
//将字符串写入文件
public static void writeFile(String s) throws IOException {
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("wdsin.txt")));
bw.write(s);
bw.close();
}
//读取文件内容
public static String readFile(String fileName) throws IOException {
File myFile=new File(fileName);
if (!myFile.exists()) {
System.err.println(fileName+"不存在!");
}
BufferedReader br=new BufferedReader(new FileReader(fileName));
String s;
while((s=br.readLine())!=null){
System.out.println(s);
}
br.close();
return s;
}
public static void main(String[] args) throws IOException {
String fileName="wdsin.txt";
writeFile(fileName);
readFile(fileName);
}
}