Java题目:替换字符串
发布网友
发布时间:2022-05-01 04:53
我来回答
共2个回答
热心网友
时间:2022-06-24 14:52
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class 替换字符串
{
private static final String FILE = "input.txt";
public static void main(String[] args)
{
try
{
Scanner sc = new Scanner(new File(FILE));
String result = "";
while(sc.hasNextLine())
{
result += sc.nextLine() + "\r\n";
}
sc.close();
Scanner sc1 = new Scanner(System.in);
System.out.print("输入人的名字:");
String name = sc1.next();
System.out.print("输入狗的名字:");
String dog = sc1.next();
sc1.close();
result = result.replaceAll("name", name).replaceAll("dog", dog);
FileWriter fw = new FileWriter(name);
fw.write(result);
fw.flush();
fw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
热心网友
时间:2022-06-24 14:53
public class FileTest {
public static void main(String[] args) throws IOException {
//读取文件
InputStream in = new FileInputStream(new File("d:/test.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String tmp = null;
StringBuilder sb = new StringBuilder();
while((tmp = br.readLine()) != null) {
sb.append(tmp);
}
br.close();
//替换文字
String content = sb.toString();
System.out.print("请输入人名:");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
content = content.replace("name", name);
System.out.print("请输入狗名:");
String dog = scanner.next();
content = content.replace("dog", dog);
scanner.close();
//写入文件
FileOutputStream out = new FileOutputStream(new File("d:/" + name + ".txt"));
out.write(content.getBytes());
out.close();
}
}