[英]Save Java txt file to folder
首先-我在Stackoverflow上愛你們所有人! 每個人都非常有幫助! 可悲的是,當我去回答問題時,它們對我來說太先進了:'(
我想將文本文件保存到文件夾-但不是絕對文件夾,例如,我要將其保存到
{課程位置} /text/out.txt
由於該程序在不同的計算機上運行,因此位置會發生變化,因此我無法將C://放在
我也知道我需要使用疑問“ \\\\”-但這在我的嘗試中不起作用
public void writeFile (int ID, int n) {
try{
String Number = Integer.toString(n);
String CID = Integer.toString(ID);
FileWriter fstream = new FileWriter("//folder//out.txt",true); //this don't work
BufferedWriter out = new BufferedWriter(fstream);
out.write(Number+"\t"+CID);
out.newLine();
out.close();
}//catch statements etc
您可以使用getAbsolutePath()函數:
FileWriter fstream = new FileWriter(new File(".").getAbsolutePath()+"//folder//out.txt",true);
我建議你看看這個話題
在代碼目錄中創建名為text的文件夾與文件系統無關。 要在{project folder}/text/out.txt
創建文件,您可以嘗試以下操作:
String savePath = System.getProperty("user.dir") + System.getProperty("file.separator") + text;
File saveLocation = new File(savePath);
if(!saveLocation.exists()){
saveLocation.mkdir();
File myFile = new File(savePath, "out.txt");
PrintWriter textFileWriter = new PrintWriter(new FileWriter(myFile));
textFileWriter.write("Hello Java");
textFileWriter.close();
}
不要忘記捕捉IOException
!
使其保存.txt到文件夾根目錄的最簡單方法是:
public class MyClass
{
public void yourMethod () throws IOException
{
FileWriter fw = null;
try
{
fw = new FileWriter ("yourTxtdocumentName.txt");
// whatever you want written into your .txt document
fw.write ("Something");
fw.write ("Something else");
System.out.println("Document completed.");
fw.close
}
catch (IOException e)
{
e.printStackTrace();
}
} // end code
} // end class
然后,您隨時可以調用此方法,它將把您編寫的任何代碼保存到項目文件夾的根目錄中。
然后,您可以在任何計算機上運行您的應用程序,它將仍然保存文檔以在任何計算機上查看。
您應該首先創建目錄,然后創建文件。 請記住首先檢查它們的存在:
new File("some.file").exists();
new File("folder").mkdir(); // creates a directory
new File("folder" + File.separator + "out.txt"); // creates a file
如果資源已經存在,則不需要創建File
對象。
File.separator
是您使用斜杠解決本地化問題的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.