eclipse 写入包 Java 内的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5291852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 15:58:22  来源:igfitidea点击:

Writing to file inside package Java

javaeclipsefilestream

提问by syousuf

Hi I am new to Java, so kindly bear me. I am reading info from a file and want to write to it.I am using eclipse.

嗨,我是 Java 新手,请耐心等待。我正在从文件中读取信息并想写入它。我正在使用 eclipse。

My directory structure is

我的目录结构是

ProjectName-->src-->Package(This is my package where my java files are)

ProjectName-->src-->Package(这是我的 java 文件所在的包)

I am trying to create a jar file. My text file is inside the package.

我正在尝试创建一个 jar 文件。我的文本文件在包内。

To read from file i am using below code.

要从文件中读取,我正在使用以下代码。

InputStream is = getClass().getResourceAsStream("BookingInfo.csv");
InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr);

Now i want to write to same file.I am doing something like this

现在我想写入同一个文件。我正在做这样的事情

String filename ="src/Package/BookingInfo.csv";    
File myFile = new File(filename);  
fw = new FileWriter(myFile,true);
fw.write(report);
fw.close();

But somehow its not updating it. Can you kindly adivise me on this.

但不知何故它没有更新它。你能就此给我建议吗?

回答by Brian Agnew

You won't be able to write back into the .jar file, unfortunately. You can write instead to a file in the filesystem, but the .jar will be immutable.

不幸的是,您将无法写回 .jar 文件。您可以改为写入文件系统中的文件,但 .jar 将是不可变的。

You couldunpack the .jar programmatically (into a temp directory), overwrite the file and then rebuild the .jar file. See the documentation on the .jar-related APIs.

可以以编程方式解压缩 .jar(到临时目录中),覆盖该文件,然后重建 .jar 文件。请参阅有关 .jar 相关 API文档。

回答by Krisz Namenyi

Your project's workspace files are not syncronized automatically, so you have to refresh in Eclipse. Than you will see the changes.

您项目的工作区文件不会自动同步,因此您必须在 Eclipse 中刷新。比你会看到的变化。

回答by Subhojit Das

You need to give full path while creating a new file inside a project. Try this code:

在项目中创建新文件时,您需要提供完整路径。试试这个代码:

File xmlFile = new File("src/com/company/project/xml/tags.xml");

File xmlFile = new File("src/com/company/project/xml/tags.xml");

And you will be able to create file in com.company.project.xml package.

您将能够在 com.company.project.xml 包中创建文件。

回答by oliholz

What about:

关于什么:

String url = getClass().getResource("BookingInfo.csv").getFile();
fw = new FileWriter(url ,true);
fw.write(report);
fw.close();