`

目录下所有文本内容替换

阅读更多
项目中所有JSP文件编码要从gb2312替换为gbk,写了个方法,记录一下备用

		replace(new File("E:\\java_workspace\\tttt\\WebRoot"), new String[]{"jsp", "html"}, new String[]{"gb2312", "GB2312"}, "GBK");

	/**
	 * 替换文件路径下所有满足条件的文件中的某些字符串
	 * @param path
	 * @param fileNameSurffix
	 * @param toReplace
	 * @param src
	 */
	public static void replace(
			File folder, final String[] fileNameSurffixes, 
			String[] oldChars, String newChar) {
		File[] subFiles = folder.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if(new File(dir + File.separator + name).isDirectory()) {
					return true;
				}
				
				if(fileNameSurffixes == null || fileNameSurffixes.length == 0) {
					return true;
				}
				
				for(String surf : fileNameSurffixes) {
					if(name.endsWith("." + surf)) {
						return true;
					}
				}

				return false;
			}
		});
		
		if(subFiles == null || subFiles.length == 0) {
			return;
		}
		
		for(File f : subFiles) {
			if(f.isFile()) {
				if(!f.canRead() || !f.canWrite()) {
					System.err.println("【不能修改】" + f.getAbsolutePath());
					continue;
				}
				
				Scanner in = null;
				StringBuffer content = new StringBuffer("");
				String line = "";
				boolean found = false;
				try { //读取并替换内容到content
					in = new Scanner(f);
					while(in.hasNextLine()) {
						line = in.nextLine();
						
						for(String oldChar : oldChars) {
							if(line.contains(oldChar)) {
								found = true;
								line = line.replace(oldChar, newChar);
							}
						}
						
						content.append(line);
						content.append("\r\n");
					}

					System.out.println("【读取】" + f.getAbsolutePath());
				} catch(Exception e) {
					System.err.println("【读取失败】" + f.getAbsolutePath());
					e.printStackTrace();
				} finally {
					if(in != null) {
						in.close();
					}
				}
				
				if(found) {
					PrintWriter out = null;
					try {
						out = new PrintWriter(new FileOutputStream(f, false));
						out.write(content.toString());
						out.flush();
						
						System.out.println("【替换】" + f.getAbsolutePath());
					} catch (Exception e) {
						System.err.println("【替换失败】" + f.getAbsolutePath());
						e.printStackTrace();
					} finally {
						if(out != null) {
							out.close();
						}
					}
				} else {
					System.out.println("【跳过】" + f.getAbsolutePath());
				}
			} else {
				replace(f, fileNameSurffixes, oldChars, newChar);
			}
		}
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics