java 文件输入流的文件位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12508096/
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-10-31 09:10:15  来源:igfitidea点击:

File location for fileinputstream

javafileinputstream

提问by mellissa

I'm doing an Android project and I have a .bin format file which I put it right at the root of my Java project (not in any folder). I tried to retrieve it using FileInputStream such as below:

我正在做一个 Android 项目,我有一个 .bin 格式的文件,我把它放在我的 Java 项目的根目录下(不在任何文件夹中)。我尝试使用 FileInputStream 检索它,如下所示:

InputStream file = new FileInputStream("filename.bin");

But it couldn't read the file.

但它无法读取文件。

Where should I put my bin file? or is there something else that I need to take note of?

我应该把我的 bin 文件放在哪里?或者还有什么我需要注意的吗?

[Edit]The error:

[编辑]错误:

Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/ref/FinalReference

[Edit] Solution: Found the solution from here >> Eclipse error: NoClassDefFoundError: java/lang/ref/FinalReference.

[编辑] 解决方案:从这里找到解决方案>> Eclipse 错误: NoClassDefFoundError: java/lang/ref/FinalReference

1. Find Running configurations -> java application
2. In the new configuration's Classpath tab, find "Android Library" under Bootstrap Entries and remove it.
3. Still in the Classpath tab, select Bootstrap Entries and click the Advanced button.
4. Choose Add Library and click OK.
5. Select JRE System Library and click Next.
6. Select Workspace Default JRE and click Finish.

回答by RNJ

FileInputStream also takes a file in to one of its constructors.

FileInputStream 还将一个文件输入到它的构造函数之一。

You can do

你可以做

File f = new File("filename.bin")
if (f.isFile()) {
    InputStream is = new FileInputStream(f);
} 
else {
    //cope with missing file
}

This way if the file ever disappears or is not where you think it is you will not get a FileNotFoundException

这样,如果文件消失或不在您认为的位置,您将不会收到 FileNotFoundException

@Srigan makes a good point though to try the / infront

@Srigan 提出了一个很好的观点,尽管尝试 / infront

回答by Srijan

The above syntax denotes that the file filename.binresides in the same folder as your code. Try giving an absolute path to the file or put the file in srcfolder and use

上述语法表示该filename.bin文件与您的代码位于同一文件夹中。尝试提供文件的绝对路径或将文件放在src文件夹中并使用

InputStream file = new FileInputStream("/filename.bin");

回答by popfalushi

To get current working directory: System.getProperty("user.dir"));

获取当前工作目录: System.getProperty("user.dir"));