Java 如何使用 InputStream 从目录中获取文件名
How to get the file name from the directory using InputStream in Java
我只需要使用 InputStream
从目录中获取文件名。
我通过使用 File
将文件名设为 abc.tx
t,如下所示,
File file = new File("F:\source\abc.txt");
file.getAbsoluteFile().getName() // getting - abc.txt
同理,我想用InputStream
得到和上面一样的文件名abc.txt
。
InputStream inputfile= new FileInputStream("F:\source\abc.txt");
Field field = inputfile.getClass().getDeclaredField("path");
field.setAccessible(true);
String filePath = (String)field.get(inputfile);
File fileName = new File(filePath);
请问如何只获取文件名?
首先,你做的事情很脆弱:
- 如果
InputStream
不是 FileInputStream
,它将失败。
- 如果未来的 Java 版本更改了
FileInputStream
的内部结构,它可能会失败。
- 如果您的代码被沙盒化,它很可能会失败。
最好保留/传递您在实例化 FileInputStream
时使用的参数值。
话虽如此,要仅获取文件名,您需要使用 File
或 Path
来提取它;例如
String justTheFileName = new File(fileName).getName();
或
String justTheFileName = Paths.get(fileName).getFileName();
我只需要使用 InputStream
从目录中获取文件名。
我通过使用 File
将文件名设为 abc.tx
t,如下所示,
File file = new File("F:\source\abc.txt");
file.getAbsoluteFile().getName() // getting - abc.txt
同理,我想用InputStream
得到和上面一样的文件名abc.txt
。
InputStream inputfile= new FileInputStream("F:\source\abc.txt");
Field field = inputfile.getClass().getDeclaredField("path");
field.setAccessible(true);
String filePath = (String)field.get(inputfile);
File fileName = new File(filePath);
请问如何只获取文件名?
首先,你做的事情很脆弱:
- 如果
InputStream
不是FileInputStream
,它将失败。 - 如果未来的 Java 版本更改了
FileInputStream
的内部结构,它可能会失败。 - 如果您的代码被沙盒化,它很可能会失败。
最好保留/传递您在实例化 FileInputStream
时使用的参数值。
话虽如此,要仅获取文件名,您需要使用 File
或 Path
来提取它;例如
String justTheFileName = new File(fileName).getName();
或
String justTheFileName = Paths.get(fileName).getFileName();