6

首先 - 我在 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
4

4 回答 4

6

您可以使用 getAbsolutePath() 函数:

 FileWriter fstream = new FileWriter(new File(".").getAbsolutePath()+"//folder//out.txt",true);

我建议你看看这个线程

于 2012-01-30T00:14:16.293 回答
0

在代码目录中创建一个名为 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

于 2015-02-20T01:55:55.943 回答
0

使其将 .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

然后,您可以随时调用此方法,它会将您编写的要写入 .txt 文档的任何内容保存到项目文件夹的根目录中。

然后,您可以在任何计算机上运行您的应用程序,它仍会保存文档以在任何计算机上查看。

于 2017-05-12T14:29:54.993 回答
-1

您应该首先创建目录,然后创建文件。请记住首先检查它们的存在:

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是解决您的斜杠本地化问题的答案。

于 2012-01-30T00:31:00.803 回答