栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java课后题第十二章:12.11(删除文本)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java课后题第十二章:12.11(删除文本)

目录

1、使用编译器调用

2、使用Command line调用

3、运行示例


1、使用编译器调用
import java.util.Scanner;

public class DeleteTxt {
    public static void main(String[] args) throws IOException {
        File sourceFile = new File("John.txt");
        File targetFile = new File("John1.txt");
        try (Scanner input = new Scanner(sourceFile);
             PrintWriter output = new PrintWriter(targetFile))
        {
            while (input.hasNext()) {
                String s1 = input.nextLine();
                String s2 = s1.replace("John", " ");
                output.println(s2);
            }
        }
    }
}

2、使用Command line调用

        1)改args.length!=3        2)原args[3]替换为空字符串

// command line
java ReplaceText.java John.txt NewJohn1.txt John
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

public class ReplaceText {
    public static void main(String[] args) throws Exception {
        if (args.length != 3) {  
            System.out.println("Usage:java ReplaceText sourceFile targetFile oldStr newStr");
            System.exit(1);
        }
        File sourceFile = new File(args[0]);
        if (!sourceFile.exists()) {
            System.out.println("Source file" + args[0] + "does not exist");
            System.exit(2);
        }
        File targetFile = new File(args[1]);
        if (targetFile.exists()) {
            System.out.println("Target file " + args[1] + " already exists");
            System.exit(3);
        }
        try (
                Scanner input = new Scanner(sourceFile);
                PrintWriter output = new PrintWriter(targetFile)) {
            while (input.hasNext()) {
                String s1 = input.nextLine();
                String s2 = s1.replaceAll(args[2], ""); 
                output.println(s2);
            }
        }
    }
}

3、运行示例
John.txt-记事本
John is a good man.
John is a good man.
NewJohn.txt-记事本
 is a good man.
 is a good man.

 

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/572891.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号