gpt4 book ai didi

java - 如何在java中使用另一个try block 中存在的文件路径

转载 作者:行者123 更新时间:2023-12-01 11:39:29 26 4
gpt4 key购买 nike

有人可以告诉我如何在另一个 block 中使用一个 try block 中存在的文件路径吗?下面是我的代码:

    try
{

Path file = Paths.get("testing.txt");
byte[] bytesFromFile = Files.readAllBytes(file);

String textFromFile = new String(bytesFromFile, StandardCharsets.UTF_8);

String s = String.format(textFromFile, "12");


Path file1 = Files.write(file, s.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);

System.out.println(file1); --> **Contains file path and I want to use this in next try block.**
}
catch (Exception ex)
{
ex.printStackTrace();
}

try {
ClassLoader loader = TestSpecification.class.getClassLoader();


input = loader.getSystemResources(file1); --> **It is throwing me an error.**


} finally {
if (input != null) {
input.close();
}
}

最佳答案

以下解决方案可能对您有帮助:

Path file1 = null;
try {
Path file = Paths.get("testing.txt");
byte[] bytesFromFile = Files.readAllBytes(file);
String textFromFile = new String(bytesFromFile, StandardCharsets.UTF_8);
String s = String.format(textFromFile, "12");
file1 = Files.write(file, s.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);

System.out.println(file1); --> **Contains file path and I want to use this in next try block.**
}
catch (Exception ex)
{
ex.printStackTrace();
}

try {
ClassLoader loader = TestSpecification.class.getClassLoader();
input = loader.getSystemResources(file1); --> **It is throwing me an error.**

} finally {
if (input != null) {
input.close();
}
}

关于java - 如何在java中使用另一个try block 中存在的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29659294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com