java 编辑字符串变量字段[已关闭]

ngynwnxp  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(102)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

3天前关闭。
Improve this question
我从一个文件中获取一个字符串形式的输入URL,并将其存储在一个变量中,我想在Java中更改URL的字段(请帮助)
https://stackoverflow.com/questions/ask?newreg=a887241a1861475
假设我得到了字符串形式的输入,并存储在
字符串变量;
现在我需要到改变变量部分(假设在网址的地方问题到答案)
如果它是硬编码的代码,我可以改变它,但我得到它从一个文件,所以我怎么能改变它
字符串localurl=storeLink.get(“dvlp”);它正在从数组获取链接
本地化。替换(“耐克“、“巴塔”);

pqwbnv8z

pqwbnv8z1#

这很简单,你可以用BufferReader读取文件,用BufferWriter写入文件。
我正在添加一个示例场景。根据您的要求自定义它。
让我们创建一个名为'urls.txt'的文本文件并填充它。

网址.txt

https://stackoverflow.com/questions/ask?newreg=a887241a1861475
https://stackoverflow.com/questions/ask?newreg=a887241a1861475
https://stackoverflow.com/questions/ask?newreg=a887241a1861475
https://stackoverflow.com/questions/ask?newreg=a887241a1861475
https://stackoverflow.com/questions/ask?newreg=a887241a1861475
https://stackoverflow.com/questions/ask?newreg=a887241a1861475
https://stackoverflow.com/questions/ask?newreg=a887241a1861475
https://stackoverflow.com/questions/ask?newreg=a887241a1861475
https://stackoverflow.com/questions/ask?newreg=a887241a1861475

URL操作符

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class UrlManipulator {
    public static void main(String[] args) throws IOException  {
        // add the path of the file 
        File file = new File("/home/user/Documents/codes/urls.txt");
        BufferedReader br = new BufferedReader(new FileReader(file)); 
        // insert the target string which is to be replced
        String target = "questions"; 
        // insert into the replacement string which is to be added
        String replacement = "answers"; 
        String url = ""; 
        String wholeFile = ""; 
        while ((url = br.readLine()) != null){
            url = url.replace(target, replacement);
            wholeFile =  wholeFile.concat(url + "\n"); 
        }
        br.close(); 
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write(wholeFile);
        bw.close(); 
    }
}

运行代码后,文本文件将更改为

https://stackoverflow.com/answers/ask?newreg=a887241a1861475
https://stackoverflow.com/answers/ask?newreg=a887241a1861475
https://stackoverflow.com/answers/ask?newreg=a887241a1861475
https://stackoverflow.com/answers/ask?newreg=a887241a1861475
https://stackoverflow.com/answers/ask?newreg=a887241a1861475
https://stackoverflow.com/answers/ask?newreg=a887241a1861475
https://stackoverflow.com/answers/ask?newreg=a887241a1861475
https://stackoverflow.com/answers/ask?newreg=a887241a1861475
https://stackoverflow.com/answers/ask?newreg=a887241a1861475

相关问题