编写Java程序,读取文本文档的内容,去除文本中包含的“广告”字样,把更改后的内容保存到一个新的文本文档中

查看本章节

查看作业目录


需求说明:

读取文本文档的内容,去除文本中包含的“广告”字样,把更改后的内容保存到一个新的文本文档中

实现思路:

  1. 在main() 方法中,使用 new File(String pathname) 构造方法,分别创建用来读取的文件实例 file 和用来写入的文件实例 newFile
  2. 编写 readTxtFile(File file) 方法读取文件内容,返回字符串
  3. 编写 writeContent(String str, File newFile) 方法写入文件,写入文件之前,使用字符串的替换函数 replace 替换‘广告’为’’,然后将替换后的字符串写入新文件中

实现代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class SaveNewFlie {
	
	public static void main(String[] args) {
		SaveNewFlie saveNewFlie = new SaveNewFlie();
		//需要读取的文本对象
		File file = new File("z:\\xin.txt");
		//需要写入新内容的文本对象
		File newFile = new File("d:\\newXin.txt");
		//判断读取的内容是否存在
		if (file.exists()) {
			//返回读取的文本内容
			String str = saveNewFlie.readTxtFile(file);
			str.replace("广告","");
			//将改变后的文本内容写入到新文件内
			saveNewFlie.writeContent(str, newFile);
			System.out.println("重写文件成功");
		} else {
			System.out.println("改文件不存在,不能读取!");
		}
	}
	//将更改后的内容写入到一个新的文件内
	public void writeContent(String str, File file) {
		FileOutputStream output = null;
		try {
			//实例化一个字节输出流
			output = new FileOutputStream(file);
			//把要写入的文本内容转换成字节数组
			byte[] temp = str.getBytes();
			//将保存在字节数组内的数据写入到新文件内
			output.write(temp);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	//读取文件内的文本内容
	public String readTxtFile(File file) {
		String str = null;
		FileInputStream input = null;
		try {
			//实例化一个字节输入流
			input = new FileInputStream(file);
			//创建一个字节数组,用来保存读取到的内容
			byte[] temp = new byte[(int)file.length()];
			//将读取到的内容保存到字节数组
			input.read(temp);
			//将字节数组转换成字符串
			str = new String(temp,"gbk");
			System.out.println("原始内容:"+str);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return str;
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_44893902/article/details/108700798