将 Java txt 文件保存到文件夹
首先 - 我爱 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
First of all - I love you all at Stackoverflow! Everyone is very helpful! Sadly when I go to answer questions they are all too advance for me :'(
I want to save the text file to a folder - but not an absolute folder for example I want to save it to
{class location}/text/out.txt
Because the program is being worked on different computers the location changes, so I can't put C:// ect
I also know I need to use doubt "\\" - but this didn't work in my attempts
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 getAbsolutePath() 函数:
我建议您看一下 这个线程
you can use getAbsolutePath() function:
and i sugest you to take a look at this thread
在代码目录中创建名为 text 的文件夹与文件系统无关。要在
{project folder}/text/out.txt
中创建文件,您可以尝试以下操作:不要忘记捕获
IOException
!Creating a folder named text in the code's directory is file system independent. To create a file in
{project folder}/text/out.txt
you can try this:Don't forget to catch the
IOException
!让它将 .txt 保存到文件夹根目录的最简单方法是这样做:
然后,您可以随时调用此方法,它会将您编写的要写入 .txt 文档的任何内容保存到您的根目录中。项目文件夹。
然后,您可以在任何计算机上运行您的应用程序,并且它仍然会保存文档以供在任何计算机上查看。
The simplest way to make it save your .txt to the root of your folder is to do this:
Then you call this method whenever you like, it will save whatever you have coded to be written into the .txt document into the root of your project folder.
You can then run your application on any computer, and it will still save the document for viewing on any computer.
您应该首先创建目录,然后创建文件。请记住首先检查它们是否存在:
如果资源已经存在,则不需要创建
File
对象。File.separator
是解决斜杠本地化问题的答案。You should first create directories and then the files. Remember to firstly check their existence:
Don't need to create a
File
object if resource already exist.File.separator
is the answer for your localization problems with slashes.