본문 바로가기
LibGdx

File handling

by ses jeon 2021. 4. 18.

github.com/libgdx/libgdx/wiki/File-handling

 

libgdx/libgdx

Desktop/Android/HTML5/iOS Java game development framework - libgdx/libgdx

github.com

Introduction

libGDX applications run on four different platforms: desktop systems (Windows, Linux, Mac OS X, headless), Android, iOS, and JavaScript/WebGL capable browsers. Each of these platforms handles file I/O a little differently.

Libgdx's Files (code) module provides the ability to:

libGDX 애플리케이션은 데스크톱 시스템 (Windows, Linux, Mac OS X, 헤드리스), Android, iOS 및 JavaScript / WebGL 지원 브라우저의 네 가지 플랫폼에서 실행됩니다. 이러한 각 플랫폼은 파일 I / O를 약간 다르게 처리합니다. Libgdx의 파일 (코드) 모듈은 다음 기능을 제공합니다.

  • Read from a file
  • Write to a file
  • Copy a file
  • Move a file
  • Delete a file
  • List files and directories
  • Check whether a file/directory exists

Before we can dive into that aspect of Libgdx, we have to first review the different notions of filesystems for all supported platforms.

Libgdx의 이러한 측면을 살펴보기 전에 먼저 지원되는 모든 플랫폼에 대한 파일 시스템의 다른 개념을 검토해야합니다.

Platform Filesystems

Here we review the filesystem paradigms of the platforms libGDX supports

여기에서는 libGDX가 지원하는 플랫폼의 파일 시스템 패러다임을 검토합니다.

Desktop (Windows, Linux, Mac OS X, Headless)

On a desktop OS, the filesystem is one big chunk of memory. Files can be referenced with paths relative to the current working directory (the directory the application was executed in) or absolute paths. Ignoring file permissions, files and directories are usually readable and writable by all applications.

데스크톱 OS에서 파일 시스템은 하나의 큰 메모리 청크입니다. 파일은 현재 작업 디렉토리 (응용 프로그램이 실행 된 디렉토리) 또는 절대 경로에 상대적인 경로로 참조 될 수 있습니다. 파일 권한을 무시하면 파일 및 디렉토리는 일반적으로 모든 응용 프로그램에서 읽고 쓸 수 있습니다.

Android

On Android the situation is a little bit more complex. Files can be stored inside the application's APK either as resources or as assets. These files are read-only. libGDX only uses the assets mechanism, as it provides raw access to the byte streams and more closely resembles a traditional filesystem. Resources better lend themselves to normal Android applications but introduce problems when used in games. Android manipulates them at load time, e.g. it automatically resizes images.

Android에서는 상황이 조금 더 복잡합니다. 파일은 리소스 또는 자산으로 애플리케이션의 APK 내에 저장할 수 있습니다. 이러한 파일은 읽기 전용입니다. libGDX는 바이트 스트림에 대한 원시 액세스를 제공하고 기존 파일 시스템과 더 유사하기 때문에 자산 메커니즘 만 사용합니다. 리소스는 일반 Android 애플리케이션에 더 적합하지만 게임에서 사용할 때 문제가 발생합니다. Android는로드 시간에이를 조작합니다. 이미지 크기를 자동으로 조정합니다.

 

Assets are stored in your Android project's assets directory and will be packaged with your APK automatically when you deploy your application and are accessible via Gdx.files.internal, a read-only directory not to be confused with what the Android documentation refers to as "internal". No other application on the Android system can access these files.

애셋은 Android 프로젝트의 애셋 디렉터리에 저장되며 애플리케이션을 배포 할 때 APK와 함께 자동으로 패키징되며, Android 문서에서 "라고 부르는 것과 혼동하지 않도록 읽기 전용 디렉터리 인 Gdx.files.internal을 통해 액세스 할 수 있습니다. 내부의". Android 시스템의 다른 애플리케이션은 이러한 파일에 액세스 할 수 없습니다.

 

Files can also be stored on what the Android documentation refers to as internal storage (accessible via Gdx.files.local in LibGDX), where they are readable and writable. Each installed application has a dedicated internal storage directory. This directory is again only accessible by that application. One can think of this storage as a private working area for the application.

또한 Android 문서에서 내부 저장소 (LibGDX의 Gdx.files.local을 통해 액세스 가능)라고 부르는 곳에 파일을 저장할 수 있으며, 여기서 읽고 쓸 수 있습니다. 설치된 각 응용 프로그램에는 전용 내부 저장소 디렉터리가 있습니다. 이 디렉토리는 해당 응용 프로그램에서만 다시 액세스 할 수 있습니다. 이 스토리지는 애플리케이션을위한 개인 작업 영역으로 생각할 수 있습니다.

 

Finally, files can be stored on the external storage, accessible via Gdx.files.external in LibGDX. The behaviour regarding external files was changed in Android over the times, hence in LibGDX:

마지막으로, LibGDX의 Gdx.files.external을 통해 액세스 할 수있는 외부 저장소에 파일을 저장할 수 있습니다. 외부 파일과 관련된 동작은 Android에서 시간이 지남에 따라 변경되었으므로 LibGDX에서 다음과 같이 변경되었습니다.

  • libGDX up to 1.9.11 uses the Android external storage directory. That is up to Android 4.3 the sd card directory, which might not always be available, and a virtual emulated sd card directory on later versions. For accessing these files, you need to add a permission to your AndroidManifest.xml file, see Permissions. From Android 6 on, even a runtime permission is needed to use the directory and starting from Android 11, access is forbidden completely for normal apps (if you want to publish on the Play Store).

최대 1.9.11의 libGDX는 Android 외부 저장소 디렉토리를 사용합니다. Android 4.3까지는 항상 사용할 수없는 sd 카드 디렉토리와 이후 버전의 가상 에뮬레이트 된 SD 카드 디렉토리입니다. 이러한 파일에 액세스하려면 AndroidManifest.xml 파일에 권한을 추가해야합니다. 권한을 참조하세요. Android 6부터는 디렉터리를 사용하기 위해 런타임 권한이 필요하고 Android 11부터는 일반 앱 (Play 스토어에 게시하려는 경우)에 대한 액세스가 완전히 금지됩니다.

  • libGDX 1.9.12 or later uses the App external storage directory. This directory (located at Android/data/data/your_package_id/) is readable and writable from your app without any further permission and changes. Other apps (like file managers) can access the files up to Android 10, from Android 11 on the directory is only accessible via USB access. Note: If the user uninstalls the app, the data saved here will be deleted if not copied to another location before by the user.

libGDX 1.9.12 이상은 앱 외부 저장소 디렉토리를 사용합니다. 이 디렉터리 (Android / data / data / your_package_id /에 있음)는 추가 권한 및 변경없이 앱에서 읽고 쓸 수 있습니다. 다른 앱 (예 : 파일 관리자)은 Android 10까지 파일에 액세스 할 수 있으며, 디렉토리의 Android 11에서는 USB 액세스를 통해서만 액세스 할 수 있습니다. 참고 : 사용자가 앱을 제거하는 경우 사용자가 이전에 다른 위치에 복사하지 않으면 여기에 저장된 데이터가 삭제됩니다.

 

The App external storage is initialized at game start for you to use, therefore Android creates an empty directory. If you don't use external files and want to suppress this behaviour, you can do so by overriding the instantiation of AndroidFiles in AndroidApplication#createFiles (1.9.14 and up):

앱 외부 저장소는 게임 시작시 사용자가 사용할 수 있도록 초기화되므로 Android는 빈 디렉터리를 생성합니다. 외부 파일을 사용하지 않고이 동작을 억제하려면 AndroidApplication # createFiles (1.9.14 이상)에서 AndroidFiles의 인스턴스화를 재정의하면됩니다.

protected AndroidFiles createFiles() { this.getFilesDir(); // workaround for Android bug #10515463 return new DefaultAndroidFiles(this.getAssets(), this, false); }

iOS

On iOS all file types are available.

Javascript/WebGL

A raw Javascript/WebGL application doesn't have a traditional filesystem concept. Instead, assets like images are referenced by URLs pointing to files on one or more servers. Modern browsers also support Local Storage which comes close to a traditional read/write filesystem. The problem with local storage is that the storage amount available by default is fairly small, not standardized, and there no (good) way to accurately query the quota. For this reason, the preferences API is currently the only way to write local data persistently on the JS platform.

libGDX does some magic under the hood to provide you with a read-only filesystem abstraction.

원시 Javascript / WebGL 애플리케이션에는 전통적인 파일 시스템 개념이 없습니다. 대신 이미지와 같은 자산은 하나 이상의 서버에있는 파일을 가리키는 URL에서 참조됩니다. 최신 브라우저는 기존 읽기 / 쓰기 파일 시스템에 가까운 로컬 스토리지도 지원합니다. 로컬 저장소의 문제는 기본적으로 사용 가능한 저장소 양이 표준화되지 않고 상당히 적으며 할당량을 정확하게 쿼리 할 수있는 (좋은) 방법이 없다는 것입니다. 이러한 이유로 환경 설정 API는 현재 JS 플랫폼에서 로컬 데이터를 지속적으로 작성하는 유일한 방법입니다. libGDX는 읽기 전용 파일 시스템 추상화를 제공하기 위해 내부적으로 약간의 마법을 수행합니다.

File (Storage) Types

A file in libGDX is represented by an instance of the FileHandle class. A FileHandle has a type which defines where the file is located. The following table illustrates the availability and location of each file type for each platform.

libGDX의 파일은 FileHandle 클래스의 인스턴스로 표시됩니다. FileHandle에는 파일의 위치를 정의하는 유형이 있습니다. 다음 표는 각 플랫폼에 대한 각 파일 유형의 가용성 및 위치를 보여줍니다.

Classpath
클래스 경로 파일은 소스 폴더에 직접 저장됩니다. 이들은 항아리와 함께 패키지화되며 항상 읽기 전용입니다. 목적이 있지만 가능하면 피해야합니다.
Classpath files are directly stored in your source folders. These get packaged with your jars and are always read-only. They have their purpose, but should be avoided if possible. Yes Yes No Yes
Internal
내부 파일은 데스크톱의 애플리케이션 루트 또는 작업 디렉토리, Android의 애셋 디렉토리 및 GWT 프로젝트의 core / assets / 디렉토리에 상대적입니다. 이러한 파일은 읽기 전용입니다. 내부 저장소에서 파일을 찾을 수없는 경우 파일 모듈은 클래스 경로에서 파일을 검색합니다. Eclipse의 자산 폴더 연결 메커니즘을 사용하는 경우 필요합니다. 프로젝트 설정을 참조하십시오.
Internal files are relative to the application’s root or working directory on desktops, relative to the assets directory on Android, and relative to the core/assets/ directory of your GWT project. These files are read-only. If a file can't be found on the internal storage, the file module falls back to searching the file on the classpath. This is necessary if one uses the asset folder linking mechanism of Eclipse, see Project Setup Yes Yes Yes Yes
Local
로컬 파일은 데스크톱의 애플리케이션 루트 또는 작업 디렉토리와 Android 애플리케이션의 내부 (개인) 저장소에 상대적으로 저장됩니다. 로컬 및 내부는 데스크톱에서 거의 동일합니다.
Local files are stored relative to the application's root or working directory on desktops and relative to the internal (private) storage of the application on Android. Note that Local and internal are mostly the same on the desktop. Yes Yes No Yes
External
외부 파일 경로는 데스크탑 시스템에서 현재 사용자의 홈 디렉토리에 상대적입니다. Android에서는 앱별 외부 저장소가 사용됩니다.
External files paths are relative to the home directory of the current user on desktop systems. On Android, the app-specific external storage is used. Yes Yes No Yes
Absolute
절대 파일에는 완전한 경로가 지정되어야합니다. 참고 : 이식성을 위해이 옵션은 반드시 필요한 경우에만 사용해야합니다.
Absolute files need to have their fully qualified paths specified.
Note: For the sake of portability, this option must be used only when absolutely necessary
Yes Yes No Yes

Type Description, file path and features Desktop Android HTML5 iOS

Absolute and classpath files are mostly used for tools such as desktop editors, that have more complex file i/o requirements. For games these can be safely ignored. The order in which you should use the types is as follows:

유형 설명, 파일 경로 및 기능 데스크톱 Android HTML5 iOS Absolute 및 classpath 파일은 대부분 더 복잡한 파일 I / O 요구 사항이있는 데스크탑 편집기와 같은 도구에 사용됩니다. 게임의 경우 무시해도됩니다. 유형을 사용해야하는 순서는 다음과 같습니다.

  • Internal Files: all the assets (images, audio files, etc.) that are packaged with your application are internal files. If you use the Setup UI, just drop them in your Android project's assets folder.

애플리케이션과 함께 패키지 된 모든 자산 (이미지, 오디오 파일 등)은 내부 파일입니다. 설정 UI를 사용하는 경우 Android 프로젝트의 자산 폴더에 놓기 만하면됩니다.

  • Local Files: if you need to write small files, e.g. save a game state, use local files. These are in general private to your application. If you want a key/value store instead, you can also look into Preferences.

작은 파일을 작성해야하는 경우 (예 : 게임 상태를 저장하고 로컬 파일을 사용합니다. 이들은 일반적으로 귀하의 응용 프로그램에 비공개입니다. 대신 키 / 값 저장소를 원하는 경우 기본 설정을 살펴볼 수도 있습니다.

  • External Files: if you need to write big files, e.g. screenshots, or download files from the web, they could go on the external storage. Note that the external storage is volatile, a user can remove it or delete the files you wrote. Because they are not cleaned up and volatile, it is usually simpler to use local file storage.

큰 파일을 작성해야하는 경우 (예 : 스크린 샷을 찍거나 웹에서 파일을 다운로드하면 외부 저장소로 이동할 수 있습니다. 외부 저장소는 휘발성이므로 사용자가이를 제거하거나 작성한 파일을 삭제할 수 있습니다. 정리되지 않고 휘발성이 없기 때문에 일반적으로 로컬 파일 저장소를 사용하는 것이 더 간단합니다.

Checking Storage availability and paths

The different storage types might not be available depending on the platform your application runs on. You can query this kind of information via the Files module:

애플리케이션이 실행되는 플랫폼에 따라 다른 스토리지 유형을 사용하지 못할 수 있습니다. 파일 모듈을 통해 이러한 종류의 정보를 쿼리 할 수 있습니다.

boolean isExtAvailable = Gdx.files.isExternalStorageAvailable(); boolean isLocAvailable = Gdx.files.isLocalStorageAvailable();

You can also query the root paths for external and local storage:

외부 및 로컬 저장소의 루트 경로를 쿼리 할 수도 있습니다.

String extRoot = Gdx.files.getExternalStoragePath(); String locRoot = Gdx.files.getLocalStoragePath();

Obtaining FileHandles

A FileHandle is obtained by using one of the aforementioned types directly from the Files module. The following code obtains a handle for the internal myfile.txt file.

FileHandle은 파일 모듈에서 직접 앞서 언급 한 유형 중 하나를 사용하여 얻습니다. 다음 코드는 내부 myfile.txt 파일에 대한 핸들을 얻습니다.

FileHandle handle = Gdx.files.internal("data/myfile.txt");

If you used the libGDX Setup application, this file will be contained in your Android project's assets folder, $ANDROID_PROJECT/assets/data to be exact. Your desktop and html projects link to this folder in Eclipse, and will pick it up automatically when executed from within Eclipse.

libGDX 설정 애플리케이션을 사용한 경우이 파일은 정확히 Android 프로젝트의 자산 폴더 $ ANDROID_PROJECT / assets / data에 포함됩니다. 데스크탑 및 html 프로젝트는 Eclipse의이 폴더에 연결되며 Eclipse 내에서 실행될 때 자동으로 선택됩니다.

FileHandle handle = Gdx.files.classpath("myfile.txt");

The “myfile.txt” file is located in the directory where the compiled classes reside or the included jar files.

"myfile.txt"파일은 컴파일 된 클래스가있는 디렉토리 또는 포함 된 jar 파일에 있습니다.

FileHandle handle = Gdx.files.external("myfile.txt");

In this case, “myfile.txt” needs to be in the users’ home directory (/home/<user>/myfile.txt on Linux, /Users/<user>/myfile.txt on OSX and C:\Users\<user>\myfile.txt on Windows) on desktop, and in the root of the SD card on Android.

이 경우 "myfile.txt"는 사용자의 홈 디렉토리 (Linux의 경우 /home/<user>/myfile.txt, OSX의 경우 /Users/<user>/myfile.txt 및 C : \ Users \)에 있어야합니다. Windows의 경우 <user> \ myfile.txt), Android의 경우 SD 카드 루트에 있습니다.

FileHandle handle = Gdx.files.absolute("/some_dir/subdir/myfile.txt");

In the case of absolute file handle, the file has to be exactly where the full path points. In /some_dir/subdir/ of the current drive on Windows or the exact path on linux, MacOS and Android.

FileHandle instances are passed to methods of classes they are responsible for reading and writing data. E.g. a FileHandle needs to be specified when loading an image via the Texture class, or when loading an audio file via the Audio module.

절대 파일 핸들의 경우 파일은 전체 경로가 가리키는 정확한 위치에 있어야합니다. Windows에서 현재 드라이브의 / some_dir / subdir / 또는 linux, MacOS 및 Android에서 정확한 경로. FileHandle 인스턴스는 데이터 읽기 및 쓰기를 담당하는 클래스의 메서드에 전달됩니다. 예 : Texture 클래스를 통해 이미지를로드 할 때 또는 Audio 모듈을 통해 오디오 파일을로드 할 때 FileHandle을 지정해야합니다.

Listing and Checking Properties of Files

Sometimes it is necessary to check for the existence of a specific file or list the contents of a directory. FileHandle provides methods to do just that in a concise way.

Here's an example that checks whether a specific file exists and whether a file is actually a directory or not.

때때로 특정 파일의 존재를 확인하거나 디렉토리의 내용을 나열해야합니다. FileHandle은이를 간결하게 수행하는 메서드를 제공합니다. 다음은 특정 파일이 있는지 여부와 파일이 실제로 디렉토리인지 여부를 확인하는 예입니다.

boolean exists = Gdx.files.external("doitexist.txt").exists(); boolean isDirectory = Gdx.files.external("test/").isDirectory();

Listing a directory is equally simple:

FileHandle[] files = Gdx.files.local("mylocaldir/").list(); for(FileHandle file: files) { // do something interesting here }

WARNING: If you don't specify a folder the list will be empty.폴더를 지정하지 않으면 목록이 비어 있습니다. 

Note: Listing of internal directories is not supported on Desktop.

We can also ask for the parent directory of a file or create a FileHandle for a file in a directory (aka "child").

내부 디렉토리 목록은 Desktop에서 지원되지 않습니다. 파일의 상위 디렉토리를 요청하거나 디렉토리 ( "자식"이라고도 함)의 파일에 대한 FileHandle을 만들 수도 있습니다.

FileHandle parent = Gdx.files.internal("data/graphics/myimage.png").parent(); FileHandle child = Gdx.files.internal("data/sounds/").child("myaudiofile.mp3");

parent would point to "data/graphics/", child would point to data/sounds/myaudiofile.mp3".

There are many more methods in FileHandle that let you check for specific attributes of a file. Please refer to the Javadocs for detail.

부모는 "data / graphics /", 자식은 data / sounds / myaudiofile.mp3 "를 가리 킵니다. FileHandle에는 파일의 특정 속성을 확인할 수있는 더 많은 메서드가 있습니다. 자세한 내용은 Javadocs를 참조하십시오.

Note: These functions are mostly unimplemented in the HTML5 back-end at the moment. Try not to rely on them too much if HTML5 will be a target of your application.

이러한 기능은 현재 HTML5 백엔드에서 대부분 구현되지 않았습니다. HTML5가 애플리케이션의 대상이 될 경우 너무 많이 의존하지 마십시오.

Error Handling

Some operations on FileHandles can fail. We adopted RuntimeExceptions to signal errors instead of checked Exceptions. Our reasoning goes like this: 90% of the time we will access files that we know exist and are readable (e.g. internal files packaged with our application).

FileHandles에 대한 일부 작업이 실패 할 수 있습니다. 확인 된 예외 대신에 오류를 알리기 위해 RuntimeExceptions를 채택했습니다. 우리의 추론은 다음과 같습니다 : 90 %의 시간 동안 우리가 존재하고 읽을 수있는 파일에 액세스합니다 (예 : 애플리케이션과 함께 패키지 된 내부 파일).

Reading from a File

After obtaining a FileHandle, we can either pass it to a class that knows how to load content from the file (e.g. an image), or read it ourselves. The latter is done through any of the input methods in the FileHandle class. The following example illustrates how to load text from an internal file:

FileHandle을 얻은 후에는 파일 (예 : 이미지)에서 콘텐츠를로드하는 방법을 알고있는 클래스에 전달하거나 직접 읽을 수 있습니다. 후자는 FileHandle 클래스의 입력 방법을 통해 수행됩니다. 다음 예는 내부 파일에서 텍스트를로드하는 방법을 보여줍니다.

FileHandle file = Gdx.files.internal("myfile.txt"); String text = file.readString();

If you have binary data, you can easily load the file into a byte array:

바이너리 데이터가있는 경우 파일을 바이트 배열로 쉽게로드 할 수 있습니다.

FileHandle file = Gdx.files.internal("myblob.bin"); byte[] bytes = file.readBytes();

The FileHandle class has many more read methods. Check the Javadocs for more information.

FileHandle 클래스에는 더 많은 읽기 메서드가 있습니다. 자세한 정보는 Javadocs를 확인하십시오.

Writing to a File

Similarly to reading files, FileHandle also provides methods to write to a file. Note that only the local, external and absolute file types support writing to a file. Writing a string to a file works as follows:

파일 읽기와 마찬가지로 FileHandle은 파일에 쓰는 메서드도 제공합니다. 로컬, 외부 및 절대 파일 유형 만 파일 쓰기를 지원합니다. 파일에 문자열을 쓰는 것은 다음과 같이 작동합니다.

FileHandle file = Gdx.files.local("myfile.txt"); file.writeString("My god, it's full of stars", false);

The second parameter of FileHandle#writeString specifies if the content should be appended to the file. If set to false, the current content of the file will be overwritten.

One can of course also write binary data to a file:

FileHandle # writeString의 두 번째 매개 변수는 콘텐츠를 파일에 추가해야하는지 여부를 지정합니다. false로 설정하면 파일의 현재 내용을 덮어 씁니다. 물론 바이너리 데이터를 파일에 쓸 수도 있습니다.

FileHandle file = Gdx.files.local("myblob.bin"); file.writeBytes(new byte[] { 20, 3, -2, 10 }, false);

There are many more methods in FileHandle that facilitate writing in different ways, e.g. using OutputStream. Again, refer to the Javadocs for details.

FileHandle에는 다양한 방식으로 쓰기를 용이하게하는 더 많은 메서드가 있습니다. OutputStream 사용. 다시 한 번, 자세한 내용은 Javadocs를 참조하십시오.

Deleting, Copying, Renaming and Moving Files/Directories

These operations are again only possible for writable file types (local, external, absolute). Note however, that the source for a copying operation can also be a read only FileHandle. A few examples:

이러한 작업은 쓰기 가능한 파일 유형 (로컬, 외부, 절대)에 대해서만 가능합니다. 그러나 복사 작업의 소스는 읽기 전용 FileHandle 일 수도 있습니다. 몇 가지 예 :

FileHandle from = Gdx.files.internal("myresource.txt"); from.copyTo(Gdx.files.external("myexternalcopy.txt")); Gdx.files.external("myexternalcopy.txt").rename("mycopy.txt"); Gdx.files.external("mycopy.txt").moveTo(Gdx.files.local("mylocalcopy.txt")); Gdx.files.local("mylocalcopy.txt").delete();

Note that source and target can be files or directories.

For more information on available methods, check the FileHandle Javadocs.

댓글