[英]Permission denied when trying to write with FileWriter/BufferedWriter in java.
[英]Cannot Write String to FileWriter/BufferedWriter
我正在嘗試制作一個將創建Google Authenticator密鑰以及對OTP進行身份驗證的應用程序。 我將所有密碼寫入帶有相應名稱的單獨文件中。
首先,我正在使用此庫。 https://github.com/aerogear/aerogear-otp-java
這是我的代碼:
public void createUserFile(String name) throws IOException
{
File file = new File("users\\" + name + ".txt");
file.createNewFile();
}
public void generateUserKey(String name)
{
try
{
File file = new File("users\\" + name + ".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fw);
String s = Base32.random();
out.write(s);
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
如果將s
的值更改為“ Hello”之類的值,那很好。 但是,它不會寫入該隨機字符串。 這就是我需要幫助的地方。 我已經花了很多時間尋找答案,卻一無所獲。
我不認為您需要createUserFile
,也不清楚您是否一定知道“ users /”文件夾(相對路徑)在哪里。 我建議您使用System.getProperty(String)
來獲取user.home
( 用戶主目錄 )。
我還建議您使用try-with-resources
語句和PrintStream
。 就像是
public void generateUserKey(String name) {
File file = new File(System.getProperty("user.home"), //
String.format("%s.txt", name));
try (PrintStream ps = new PrintStream(file)) {
ps.print(Base32.random());
} catch (IOException e) {
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.