package
lianxi;
import
java.io.BufferedReader;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
java.io.InputStreamReader;
import
java.io.OutputStreamWriter;
import
java.io.PrintWriter;
import
java.util.Scanner;
/**
*
读写文件,处理FileNotFoundException异常
*
@author xiaoyu
*
*/
public
class
ReadWriterFile {
public
static
void
main(String[] args)
throws
Exception {
ReadWriterFile
rwf =
new
ReadWriterFile();
rwf.readFile();
rwf.writeFile();
}
public
void
readFile()
throws
IOException {
Scanner
scanner =
new
Scanner(System.in);
System.out.println(
"请输入要读取的文件名:"
);
String
name = scanner.nextLine();
BufferedReader
br =
null
;
while
(br
==
null
)
{
try
{
br
=
new
BufferedReader(
new
InputStreamReader(
new
FileInputStream(name)));
}
catch
(FileNotFoundException e) {
System.out.println(br);
System.out.println(
"读取文件错误,请重新输入:"
);
name
= scanner.nextLine();
}
}
System.out.println(
"读取文件成功!"
);
while
(
true
)
{
String
line = br.readLine();
if
(line
==
null
)
{
break
;
}
System.out.println(line);
}
br.close();
}
public
void
writeFile()
throws
IOException {
Scanner
scanner =
new
Scanner(System.in);
System.out.println(
"请输入文件名:"
);
PrintWriter
pw =
null
;
String
name;
while
(pw
==
null
)
{
try
{
name
= scanner.nextLine();
pw
=
new
PrintWriter(
new
OutputStreamWriter(
new
FileOutputStream(name,
true
)));
}
catch
(FileNotFoundException e) {
e.printStackTrace();
System.out.println(
"文件格式错误,请重新输入:"
);
name
= scanner.nextLine();
pw
=
null
;
}
}
System.out.println(
"创建或读取文件成功!"
);
pw.write(
"don't
worry,"
);
pw.write(
"be
happy!"
);
pw.flush();
pw.close();
}
}