下面的代码可以搜索这些值,但是现在我必须替换正在搜索的值。请帮助我是java的新手。这应该像任何具有搜索和替换功能的文本编辑器一样工作。
import org.junit.BeforeClass;
答案 0 :(得分:1)
你可以试试这个:
public class TestClass {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Path to be searched");
String directory = scanner.next();
System.out.println("Enter String to be searched");
String searchString = scanner.next();
searchDirectory(directory, searchString);
}
static void searchDirectory(String directory, String searchString) {
File dir = new File(directory);
if (!dir.isDirectory()) {
System.err.println("PATH ENTERED is not directory");
return;
}
try {
for (File file : dir.listFiles()) {
if (!file.isDirectory()) {
String fileName = file.getName().toLowerCase();
if (fileName.endsWith((".txt"))
|| fileName.endsWith((".log"))) {
@SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int Count = 0,
index = -1;
String replacedText = "";
boolean hasValue = false;
while ((line = br.readLine()) != null) {
Count++;
index = line.indexOf(searchString);
if (index != -1) {
System.out.println("Text '" + searchString + "' Found at position " + index + " in file " + fileName + " at Line No " + Count);
line.replace(searchString, newString);
hasValue = true;
}
replacedText += line;
br.close();
if (hasValue) {
FileWriter writer = new FileWriter(file);
writer.write(replacedText);
writer.close();
}
}
}
}
else {
System.err.println("TestClass.searchDirectory(DIR)" + file.getAbsolutePath());
// searchDirectory(file.getAbsolutePath(), searchString);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}