1
ABC
2
public class TestMyFile {
public static void main(String[] args) {
File file;
file = new File("hello.txt");
file.exists();
if(file.exists()){
System.out.println(file.getAbsolutePath());
}
}
}
10
FileWriter:一次可写入多个字符,不支持换行。
PrintWriter:支持输出后换行。
OutputStreamWriter:可将字节流转换为字符流,且可以设置字符的编码方式。
11
字节流
12

14
public class TestWriter {
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream("test.txt");
InputStreamReader ir = new InputStreamReader(in, "GBK");
BufferedReader br = new BufferedReader(ir);
OutputStream out = new FileOutputStream("test2.txt");
OutputStreamWriter ow = new OutputStreamWriter(out, "UTF-8");
PrintWriter p = new PrintWriter(ow);
for(;;){
String s = br.readLine();
if(s == null){
break;
}
p.println(s);
}
br.close();
p.close();
}
}
17
public class TestT17 {
public static void main(String[] args) throws IOException {
Reader r = new FileReader("worldcup.txt");
BufferedReader br = new BufferedReader(r);
Scanner input = new Scanner(System.in);
String in = input.next();
for(;;){
String s = br.readLine();
if(s == null){
System.out.println("没有举办世界杯");
break;
}
String[] ss = s.split("/");
String prefix = ss[0];
String suffix = ss[1];
if(prefix.equals(in)){
System.out.println(suffix);
break;
}
}
}
}
18
public class TestT18 {
public static void main(String[] args) throws IOException {
File f = new File("example.jpg");
FileInputStream in = new FileInputStream(f);
if(f.exists()){
File newf = new File("copy_" + f.getName());
newf.createNewFile();
FileOutputStream out = new FileOutputStream(newf);
BufferedOutputStream bo = new BufferedOutputStream(out);
for(;;){
int result = in.read();
if(result == -1){
break;
}
bo.write(result);
}
in.close();
bo.close();
}
}
}
笔记

本文详细介绍了使用Java进行文件读写的各种方法,包括利用File类检查文件存在性,不同类型的Writer类特性对比,以及如何通过InputStream和OutputStream实现文件复制。通过具体代码示例,展示了如何读取文件内容并将其写入新文件,同时处理各种可能出现的异常。
262

被折叠的 条评论
为什么被折叠?



