#千锋逆战班,作业3.17#

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
		}
	}

}
笔记

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值