简体   繁体   English

在Java中使用文件路径的最佳方法是什么?

[英]What is the best way to work with file paths in java?

I believe it's the File class but I heard that is very expensive in memory. 我相信这是File类,但我听说这在内存中非常昂贵。

Is there a better way to work with file paths? 有没有更好的方法来处理文件路径?

It's hard to say without knowing what you want to do, but please do not prematurely optimize. 在不知道自己想做什么的情况下很难说,但请不要过早优化。 I doubt the memory use of a File object will be at all noticeable in your application. 我怀疑File对象的内存使用在您的应用程序中是否会很明显。

The File class doesn't hold much data in and of itself. File类本身并不包含太多数据。 It has all of two instance fields. 它具有两个实例字段。 If all you're worried about is memory, it doesn't look like it's much of a problem. 如果您担心的只是内存,那么看起来就不成问题了。 Nothing is loaded from the file system till you open a stream or a channel. 在打开流或通道之前,不会从文件系统加载任何内容。

The File class might be expensive enough that you don't want to use it in order to store every file on your hard drive in memory. File类可能非常昂贵,以至于您不想使用它来将硬盘上的每个文件存储在内存中。 I know I've had issues with that, particularly when I tried to use a tree of File objects. 我知道我遇到了问题,尤其是当我尝试使用File对象树时。 If you do encounter a situation where using the file class is too expensive, consider just using Strings, and converting to Files at need. 如果确实遇到了使用文件类太昂贵的情况,请考虑只使用字符串,然后根据需要转换为文件。 But having that be the optimization that makes your program become practical is probably a sign that you have bigger issues. 但是将其作为使您的程序变得实用的优化可能表明您有更大的问题。 It is far more likely to have the overhead associated with the structure holding objects to be an issue. 与持有对象的结构相关联的开销很可能成为问题。

The only time I know where File uses a lot of memory is when you use File.list()... 我唯一知道File在哪里使用大量内存的地方是在您使用File.list()时...

See these for some solutions: 请参阅以下解决方案:

Is there a workaround for Java's poor performance on walking huge directories? 有没有针对Java在大型目录上行走时性能较差的解决方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中使用XML配置文件到我的应用程序的最佳方法是什么? - What is the best way to work with xml configurations file to my application in java? 不连续地在Java中写入文件的最佳方法是什么? - what is the best way to write to a file in java uncontinuously? 用Java标记文本文件的最佳方法是什么? - What is the best way to tokenize a text file in Java? 用Java构建HTML文件的最佳方法是什么? - What is the best way to build an HTML file with Java? 使用Java传输文件的最佳方法是什么? - What is the best way to transfer a file using Java? 在Java中读取文件的最佳方法是什么? - What is the best way to read a file in Java? 用Java写入文件的最佳方法是什么? - What is the best way to write to a file in Java? 在Java Web应用程序中处理图像的最佳方法是什么:存储在Blob字段中还是仅存储在其路径中? - What's the best way to deal with images in a Java web app: storing in Blob fields or just its paths? 解决所有Java字节都已签名这一事实的最佳方法是什么? - What is the best way to work around the fact that ALL Java bytes are signed? 解决 Java 的“按值传递”问题的最佳方法是什么? - What is the best way to work around Java's 'pass-by-valueness'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM