将Java文本文件保存到文件夹中

6

首先,我非常喜欢Stack Overflow上的所有人!每个人都非常乐于助人!不幸的是,当我试图回答问题时,它们对我来说都太高级了 :'(

我想将文本文件保存到一个文件夹中,但不是绝对文件夹。例如,我想保存到

{类位置}/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个回答

6

您可以使用getAbsolutePath()函数:

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

我建议您查看这个线程,它与获取正在运行的JAR文件路径有关。


超级惊人的东西!谢谢!! - Rabiani

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

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文档中,并保存在项目文件夹的根目录中。

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


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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接