我正在尝试编写一个JSP,以使用扫描仪读取文件并替换字符串。以下是我正在尝试的。 我可以使用扫描仪找到字符串,但不会将其写入文件。该文件始终为空。我想递归地搜索文件夹中的文件并替换匹配的字符串。感谢您的帮助。
<%
out.println("File Details <br>");
String resp = single("C:/Users/path");
out.println(resp);
%>
<%!
public static ArrayList<String> fileList = new ArrayList<String>();
public static String single(String URL) {
System.out.println(URL);
String respStr="";
fileList.clear();
java.io.File file;
java.io.File dir = new java.io.File(URL);
String[] list = dir.list();
for (String filepath : readDirectoryContents(dir,fileList)) {
try {
Path path = Paths.get(filepath);
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
String searchStr = "searchtext";
Scanner scan = new Scanner(new File(filepath));
PrintWriter writer = new PrintWriter(filepath, "UTF-8");
while(scan.hasNext()){
String line = scan.nextLine().toLowerCase().toString();
if(line.contains(searchStr)){
content = content.replaceAll("searchtext", "replacetext");
respStr += filepath;
writer.println(line);
writer.printf("pi is %.3f\n", 3.1415926);
}
}
writer.close();
}
catch (Exception e) {
respStr += filepath;
continue;
}
}
return respStr;
}
public static ArrayList<String> readDirectoryContents(File dir,ArrayList<String> fileList) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
readDirectoryContents(file,fileList);
} else {
fileList.add(file.getCanonicalPath());
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return fileList;
}
%>
答案 0 :(得分:0)
希望这就是您要寻找的
<%
out.println("File Details <br>");
String resp = single("C:/Users/path");
out.println(resp);
%>
<%!
public static ArrayList<String> fileList = new ArrayList<String>();
public static String single(String URL) {
System.out.println(URL);
String respStr="";
fileList.clear();
java.io.File file;
java.io.File dir = new java.io.File(URL);
String[] list = dir.list();
for (String filepath : readDirectoryContents(dir,fileList)) {
try {
Path path = Paths.get(filepath);
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
String searchStr = "searchtext";
Scanner scan = new Scanner(new File(filepath));
PrintWriter writer = new PrintWriter(filepath, "UTF-8");
if(content.contains(searchStr)){
content = content.replaceAll("searchtext","replacetext");
respStr += filepath;
// writer.printf("pi is %.3f\n", 3.1415926);
}
writer.println(content);
writer.close();
}
catch (Exception e) {
respStr += filepath;
continue;
}
}
return respStr;
}
public static ArrayList<String> readDirectoryContents(File dir,ArrayList<String> fileList) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
readDirectoryContents(file,fileList);
} else {
fileList.add(file.getCanonicalPath());
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return fileList;
}
%>