读取时文件名中的随机字符 - java

时间:2015-08-26 14:01:23

标签: java random character text-files java.util.scanner

我正在尝试从特定位置读取文本文件。但在文件名末尾,字符未确定。 防爆。它可以是

Custom Summary Report -- UAT -- 2015-08-26d.txt
Custom Summary Report -- UAT -- 2015-08-26f.txt
Custom Summary Report -- UAT -- 2015-08-26.txt
Custom Summary Report -- UAT -- 2015-08-26c.txt

因此,最后一个字符可以是任何字母或无字母。

我正在使用scanner来读取该文本文件。在文件路径中,我不知道要以字符串形式传递什么。

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();

String filepath = "C:/Custom Summary Report -- UAT -- "+dateFormat.format(date)+X+".txt";


// creating File instance to reference text file in Java
File text = new File(filepath);

// Creating Scanner instance to read File in Java
Scanner scnr = new Scanner(text);

在String文件路径中,字符X是可以是任何内容的字符。 (即任何alpahbet或没有。)

因此,我在String filepath中提到的X可以是我在特定位置不知道的任何内容。所以我想阅读那个文件。因为我不知道角色扫描仪会抛出错误。

我想要一个可以在该特定位置使用任何字符并且可以读取文件的代码。

2 个答案:

答案 0 :(得分:2)

试试这个:g将是您正在寻找的那个,但只有当您只找到一个文件时它才有效:

  File f = null;
  File g = null;
  File[] paths;

  try{      
     // create new file
     f = new File("c:/");


     // returns pathnames for files and directory
     paths = f.listFiles();


     // for each pathname in pathname array
     for(File file:paths) {
        if(file.getAbsolutePath().startsWith("C:/Custom Summary Report -- UAT -- ") {
           g=file;
           System.out.println(g);
           break;
        }
     }
  }catch(Exception e){
     // if any error occurs
     e.printStackTrace();
  }

答案 1 :(得分:0)

最后,我修改了解决方案并提出了这个答案。

    File f = null;
    File filepath = null;
    File[] paths;


    try{      
       // create new file
       f = new File("C:/");

       DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();


       // returns pathnames for files and directory
       paths = f.listFiles();


       // for each pathname in pathname array
       for(File file:paths) {
          if(file.getAbsolutePath().contains("Custom Summary Report -- UAT -- "+dateFormat.format(date))) {
             filepath=file;
             System.out.println(filepath);
             break;
          }
       }
    }catch(Exception e){
       // if any error occurs
       e.printStackTrace();
    }


    // Creating Scanner instance to read File in Java
    Scanner scnr = new Scanner(filepath);