英文:
Java Write File in Linux
问题
以下是您要翻译的内容:
在尝试在 Windows 上编写文件并成功写入文件并追加内容后,当切换到 Linux 环境时,我发现没有看到任何已创建的文件,也没有错误或异常。
以下是我在 Windows 上编写文件的方式,这是有效的:
HashMap<String, Object> map = new Gson().fromJson(dynamicJson, HashMap.class);
String keys = map.keySet().stream().collect(Collectors.joining(", "));
String values = map.values().stream().map(obj -> String.valueOf(obj)).collect(Collectors.joining(", "));
File file = new File("D:\\report-temp.csv");
try (FileWriter fw = new FileWriter("D:\\report-temp.csv", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)) {
if (file.length() == 0) {
out.println(keys);
out.println(values);
} else {
out.println(values);
}
} catch (IOException e) {
}
当我在 Linux 上运行此代码时,我将文件位置更改为 /home/xx/hashan/
,但在 Linux 上没有创建文件。
英文:
I need to write file and append content when I tried on windwos and file successfully written and append the content as well but when it comes to linux environment I can't see any file created and no error or exception as well.
This is how I write file on windows this workes
HashMap<String, Object> map = new Gson().fromJson(dynamicJson, HashMap.class);
String keys = map.keySet().stream().collect(Collectors.joining(", "));
String values = map.values().stream().map(obj ->
String.valueOf(obj)).collect(Collectors.joining(", "));
File file = new File("D:\\report-temp.csv");
try (FileWriter fw = new FileWriter("D:\\report-temp.csv", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)) {
if (file.length() == 0) {
out.println(keys);
out.println(values);
} else {
out.println(values);
}
} catch (IOException e) {
}
when I run this on linux I've changed file location as /home/xx/hashan/
but I no file created on linux.
答案1
得分: 6
I can't see any file created and no error or exception as well.
你弄错了;有一个错误。
} catch (IOException e) {}
但实际上你特意编写了代码来忽略它们!
不要这样做。完全删除那个catch块。如果然后你得到编译错误需要处理该异常,就在方法签名中添加throws IOException
。继续添加直到错误消失(一旦你在main
方法中添加了throws IOException
,你应该这样做)。
问题可能与缺少的目录或访问权限有关,你得到的异常将使这一点显而易见,所以你需要做的就是删除那个愚蠢的代码行。
英文:
> I can't see any file created and no error or exception as well.
You're mistaken; there is an error.
> } catch (IOException e) {}
but you actually went out of your way to write code to ignore them!
Don't do that. Get rid of that catch entirely. If you then get compiler errors that you need to handle that exception, add throws IOException
to the method signature. Keep adding those until the errors go away (that'll happen once you add throws IOException
to your main
method, which you should do.
The problem is probably related to a missing directory or access rights, which the exception you get will make obvious, so all you need to do is remove that silly line of code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论