繁体   English   中英

替换文件中的单词(基于位置/长度/行)

[英]Replace a word (based on position/length/line) in a file

我想写一个 java 代码,它应该允许用空格替换文件中的一个单词(以 position 为特征,长度和行)。

我写了一段代码来定位要替换的词。 但是我该如何替换那个词呢? 我应该复制并写入另一个文件吗?

我知道如何替换“字符串行”中的单词,但我无法在文件中替换它。这是当前代码:

File file = new File("myFile");    
FileReader fr = new FileReader(file);  
BufferedReader br = new BufferedReader(fr);  
String line;
        
int position = 4 ;
int length = 10 ;  
int line_number = 1 ; 

String word = "" ;
int n=0 ;
int line_x = 1 ;


while((line = br.readLine()) != null)
{
    if(line_x==line_number)
    {
        for(int i=0 ;i<line.length();i++)
        {
            while(i==position)
            {
                if (n<length)
                {
                    word = word + line.charAt(i+n)  ;
                }
                else
                {
                    break;
                    // Replace the word in the file with spaces
                }
                n++;
            }   
       } 
                
    }
    line_x++ ;
}
        
fr.close();  

您是否尝试过使用 FileWritter?

https://www.geeksforgeeks.org/filewriter-class-in-java/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM