Java——第六章(异常处理和文件IO流操作)—项目案例

本文通过四个项目案例介绍了Java中的异常处理和文件IO流操作。首先,创建并写入文件1.doc,再读取内容反转后写入2.doc;接着,实现了合并两个文件内容的功能;随后,生成5000个随机整数存入a.txt,并计算统计信息;最后,演示了从网络下载资源并提取中文内容的示例。
摘要由CSDN通过智能技术生成


1.. x:/a/b/c  创建一个文件 1.doc, 键盘输入两个字符串, 写入1.doc中, 两字符串在文件中是两行,    


你从1.doc中全部读出来,把每一个字符串都颠倒  写入2.doc中, 从2.doc  在读出来打印。


代码:



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class Demo05 {
	public static final String path = "G:/a/b/c";
	public static final String path1 = "G:/a/b/c/1.doc";
	public static final String path2 = "G:/a/b/c/2.doc";

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		System.out.println("输入两个字符串");
		String str = sc.next();
		String str1 = sc.next();
		CreatDir(path);
		String contant = str + "\r\n" + str1;
		FileOutputStream fos = new FileOutputStream(path1);
		Write(fos, contant);

		FileInputStream fis = new FileInputStream(path1);
		String contant1 = Read(fis);

		String[] ss = contant1.split("\n");
		String line1 = ss[0];
		String line2 = ss[1];
		System.out.println("第一个字符串: " + line1);
		System.out.println("第二个字符串: " + line2);
		System.out.println("第一个字符串颠倒后: " + DianDao(line1));
		System.out.println("第二个字符串颠倒后: " + DianDao(line2));

		FileOutputStream fos1 = new FileOutputStream(path2,true);
		String ss1 = line1+"\r\n"+line2;
		Write(fos1, ss1);
		

	}

	public static String Read(FileInputStream fis) throws IOException {
		byte[] b = new byte[1024];
		int len;
		String contant1 = "";
		while ((len = fis.read(b)) != -1) {
			contant1 += new String(b, 0, len);
		}
		System.out.println(contant1);
		return contant1;
	}

	public static void CreatDir(String path) {
		new File(path).mkdirs();
	}

	public static void CreatFile(String path) {
		try {
			new File(path).createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void Write(FileOutputStream fos, String contant) {

		try {
			fos.write(contant.getBytes());
			fos.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				fos.close();
			} catch (IOException e) {
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值