当前位置:   article > 正文

Java读写文件_inputstreamreader resourceasstream = new inputstre

inputstreamreader resourceasstream = new inputstreamreader(thread.currentthr

1. 知道文件确定路径

如果是读取xml文件,可以读取inputStream,再用XMLConfiguration处理

  1. import java.io.InputStream;
  2. import org.apache.commons.configuration.XMLConfiguration;
  3. // 由path获取inputStream
  4. InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
  5. // 由inputStream创建xml处理器
  6. XMLConfiguration xmlConfiguration = new XMLConfiguration();
  7. xmlConfiguration.load(in);

或则使用InputStreamReader逐行处理

  1. // 读
  2. InputStreamReader inReader = new InputStreamReader(new FileInputStream(path), "UTF8");
  3. BufferedReader buReader = new BufferedReader(inReader);
  4. try {
  5. String fromLine = null;
  6. while ((fromLine = buReader.readLine()) != null) {
  7. // 使用formLine
  8. }
  9. } finally{
  10. buReader.close();
  11. inReader.close();
  12. }
  13. // 写
  14. OutputStreamWriter outWriter = new OutputStreamWriter(new FileOutputStream(path),
  15. "UTF8");
  16. BufferedWriter buWriter = new BufferedWriter(outWriter);
  17. String toLine = "something to write";
  18. try {
  19. buWriter.write(toLine);
  20. } finally {
  21. buWriter.close();
  22. outWriter.close();
  23. }

2. 不知道文件确定路径,需要扫描

  1. Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(dirPath);
  2. recursive = true;
  3. if (dirs.hasMoreElements()) {
  4. URL url = dirs.nextElement();
  5. String protocol = url.getProtocol();
  6. if ("file".equals(protocol)) {
  7. String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
  8. File dir = new File(filePath);
  9. if (!dir.exists() || !dir.isDirectory()) {
  10. return;
  11. }
  12. File[] subDirs = dir.listFiles(new FileFilter() {
  13. @Override
  14. public boolean accept(File file) {
  15. return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
  16. }
  17. });
  18. if (subDirs == null || subDirs.length == 0) {
  19. return;
  20. }
  21. for (File f : subDirs) {
  22. if (f.isDirectory()) {
  23. // 递归处理文件夹
  24. continue;
  25. }
  26. className = f.getName();
  27. className = packageName + "." + className.substring(0, className.length() - 6);
  28. // 处理文件
  29. Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
  30. }
  31. }
  32. }

或则递归访问所有文件及子文件

  1. handle(File file) {
  2. if (file.isFile) {
  3. // 只处理.java结尾的代码文件
  4. if (!file.getPath().endsWith(".java")) {
  5. return;
  6. }
  7. // 处理逻辑
  8. } else {
  9. File[] files = file.listFiles();
  10. if (files == null) {
  11. return;
  12. }
  13. for (File subFile : files) {
  14. handle(subFile);
  15. }
  16. }
  17. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/147253
推荐阅读
相关标签
  

闽ICP备14008679号