首页 > 其他分享 >libgdx——FileHanle详解

libgdx——FileHanle详解

时间:2023-08-01 13:32:01浏览次数:42  
标签:files Gdx libgdx 详解 file FileHandle txt internal FileHanle


File handling


Table of Contents

a note from the translation

Wiki Style Guide

  • Developer's Guide
  • Configuration & Querying OpenGL ??
  • Direct Access ??
  • Utility Classes
  • 2D Graphics
  • 3D Graphics
  • Tools
  • Extensions
  • Articles
  • Deprecated (May be outdated)
  • Misc



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的files模块提供的功能有

  • 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.

Platform Filesystems

Here we review the filesystem paradigms of the platforms Libgdx supports

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.

Android

On Android the situation is a little bit more complex. Files can be stored inside the application'sAPK 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.

assets

Files can also be stored on the internal storage, 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.

Finally, files can be stored on the external storage, such as an SD-card. External storage might not always be available, e.g. the user could pull out the SD-card. Files in this storage location should thus be considered volatile. You will need to add a permission to your AndroidManifest.xml file to be allowed to write to the external storage, see Permissions

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.

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

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.

Type

Description, file path and features

Desktop

Android

HTML5

iOS

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

Internal files are relative to the application’s root or working directory on desktops, relative to theassets directory on Android, and relative to the war/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

Local files are stored relative to the application's root or working

Yes

Yes

No

Yes

External

External files paths are relative to the [SD card root](http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory(\)) on Android and to the home directory of the current user on desktop systems.

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

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:

  • 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.
  • Local Files: if you need to write small files to 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 should go on the external storage. Note that the external storage is volatile, a user can remove it or delete the files you wrote.

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 获取FileHandles

FileHandle is obtained by using one of the aforementioned types directly from the Files


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


assets folder, $ANDROID_PROJECT/assets/data


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.



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


myfile.txt” needs to be in the users’ home directory (/home/<user>/myfile.txt on linux or \Users\<user>\myfile.txt


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


/some_dir/subdir/

FileHandle instances are passed to methods of classes the 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.

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.



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
}



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").



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.

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

Error Handling

RuntimeExceptions

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 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.

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 file = Gdx.files.local("myfile.txt");
file.writeString("My god, it's full of stars", false);


FileHandle#writeString

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



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


OutputStream. Again, refer to the Javadocs for details.

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 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.

举例


package com.example.groupactiontest;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL10;

public class MyGame implements ApplicationListener {

	@Override
	public void create() {
//		FileHandle file = Gdx.files.internal("myfile.txt");
		
//		System.out.println( "Gdx.files.isExternalStorageAvailable()---->外部存储是否可用: " + Gdx.files.isExternalStorageAvailable());
//		System.out.println( "Gdx.files.isLocalStorageAvailable()----->本地存储是否可用"+ Gdx.files.isLocalStorageAvailable());
//		System.out.println(Gdx.files.getExternalStoragePath());// /mnt/sdcard/
//		System.out.println(Gdx.files.getLocalStoragePath());// /data/data/com.example.groupactiontest/files/
     
		
		
//		System.out.println( "--------------->"+ file.isDirectory());//file.isDirectory()判断这个文件是否为一个目录(文件夹)
//		System.out.println("------------------>" + file.exists());// file.exists() 判断这个文件是否存在
		
		FileHandle[] files = Gdx.files.internal("").list();//list() 列出目录下的所有文件(Listing of internal directories is not supported on Desktop.)
		
//		for(FileHandle file1 : files){
//			System.out.println("-------->"+file1.name());//file1.name() 获取文件的名字
//		}
		
//		FileHandle file = Gdx.files.internal("data/myfile.txt");
//		System.out.println( "---------------->"+ file.parent().name());//file.parent()获取当前节点的父亲节点
		
//		FileHandle file = Gdx.files.internal("data");
		/**
		 * file.child("myfile.txt"):获取当前节点的名为myfile.txt的孩子节点
		 * file.delete(): 删除某一个节点.(注意: 不能删除internal中的文件)
		 */
//		System.out.println(file.child("myfile.txt").delete());
		
//		FileHandle file = Gdx.files.internal("myfile1.txt");
//		System.out.println("-------->" + file.readString());//file.readString()读取文本文件的内容
		
//		FileHandle file = Gdx.files.external("myfile.txt");//这一句记得在androidmanefest中加上读写SD卡的权限
//		file.writeString("hahahahha ", false);//好像无法成功写入的样子(细心的操作,是可以操作成功的...)
		
//		FileHandle from = Gdx.files.internal("myfile1.txt");
//		from.copyTo(Gdx.files.external("myfile.txt"));//from.copyTo()将from中的文本复制到external中的myfile.txt中
		
//		Gdx.files.external("myfile.txt").moveTo(Gdx.files.local("1.txt"));//将external中的myfile.txt移动到local中,并重新命名为1.txt
//		System.out.println( "----------->" + Gdx.files.local("1.txt").exists());//由于我在DDMS上无法直接看到是否有1.txt文件存在.所以我就写了这么两句,事实证明它是存在的
//		System.out.println(Gdx.files.local("1.txt").readString());
		
//		Gdx.files.local("1.txt").delete();//删除local中名为1.txt的文件
//		System.out.println("------------->" + Gdx.files.local("1.txt").exists());//用来判断该文件是否已经删除
		
//		Gdx.files.internal("myfile1.txt").copyTo(Gdx.files.external("zzt.txt"));
		Gdx.files.external("hjd.txt").writeString("haung jundong is handsome boy", true);
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub

	}

	@Override
	public void render() {
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
	}

	@Override
	public void resize(int arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void resume() {
		// TODO Auto-generated method stub

	}

}





标签:files,Gdx,libgdx,详解,file,FileHandle,txt,internal,FileHanle
From: https://blog.51cto.com/u_5290007/6920356

相关文章

  • SpringBoot进行参数校验的方法详解
    https://www.jb51.net/article/246275.htm在日常的接口开发中,为了防止非法参数对业务造成影响,经常需要对接口的参数进行校验。本文通过示例详细讲解了SpringBoot如何进行参数校验的,感兴趣的可以学习一下 +目录介绍在日常的接口开发中,为了防止非法参数对业务造成影响,经常......
  • Linux 6.6+ Oracle RAC 12c搭建详解
    1. RedHatEnterpriseLinuxServerrelease6.6x86_64两台2. Oracle12.1.0.13. ASM存储方式4. 软件下载:http://www.oracle.com/technetwork/database/enterprise-edition/downloads/oracle12c-linux-12201-3608234.html 5. 基础安装包yum-yinstallbinutils.x86......
  • Mybatis学习(1)——mybatis介绍 & 入门案例 & 全局配置文件详解 & 增删改查 + mybatis事
    Mybatis学习(1)——mybatis介绍&入门案例&全局配置文件详解&增删改查+mybatis事务&mapper.xml文件#{}和${}&动态SQL入门原文链接:https://blog.csdn.net/Pireley/article/details/131520252目录引出一、mybatis是啥1.官网&ORM(ObjectRelationMapping)对象关......
  • Java中面向对象详解
    一.定义面向对象是:将事务高度抽象化的编程模式将问题分解成一个个小步骤,对每个步骤进行抽象,形成对象,通过不同的对象之间调用,组合解决问题。在进行面向对象进行编程时,要把属性、行为等封装成对象,然后基于这些对象及对象的能力进行业务逻辑的实现。创建一次,重复使用二.面向......
  • Mapper.xml详解 一对一 多对一 多对多
    Mapper.xml详解Mapper.xml详解一对一多对一多对多原文链接:https://blog.csdn.net/qq_36850813/article/details/80037363 我们知道,每一款框架产品在实际开发中,都是通过XML文件来培训框架的相关流程的,MyBatis也不例外,主要有两个配置文件:config.xml和Mapper.xml,当然,这两种配......
  • JavaScript 浅拷贝和深拷贝详解
    一、基本数据类型和引用数据类型基本数据类型:1.Number(数字类型)2.String(字符串类型)3.Boolean(布尔类型)4.Null(空类型)5.Undefined(未定义类型)6.Symbol(符号类型)引用数据类型:Object(对象类型):表示一组无序的键值对,例如{name:'张三',age:18}。基本数据类型是简单的数据类型,它......
  • java 代理(静态代理、动态代理的不同实现)详解及示例
    文章目录一、代理构成1、代理介绍2、应用场景介绍二、静态代理1、示例1)、售票服务2)、售票3)、代售点服务4)、静态代理实现1、maven依赖2、实现三、动态代理1、InvocationHandler角色2、InvocationHandler的作用3、JDK的动态代理创建机制----通过接口1)、Proxy2)、InvocationHandler3)......
  • Spring IOC实现原理详解之IOC体系结构设计 : 关于bean的生成我自己的理解;
    1、系统根据bean的配置信息(xml文件,groovy等),经过资源加载、解析配置后生成了一个关于bean的容器。2、bean容器会根据配置信息生成一个bean实例;3、将bean实例 和 一些其他配置信息生成的一些特殊的bean实例 都放入到bean的容器中;4、其他的类需要调用这些bean的时候,根据申......
  • HTTP协议详解
    HTTP协议详解我们在进行两台主机进行数据交互的时候,会遇到很多问题。如数据丢包,数据重复,数据完整性校验,数字转换模拟信号,信号衰竭等。为了简化网络的复杂度,网络通信的不同方面被分解为多层次结构,每一层只与紧挨着是上层或者下层交互,将网络分层,这样就可以修改,甚至替换某一层的......
  • 【补充】on_delete的参数详解
    【补充】on_delete的参数详解models.CASCADE(级联删除):当删除与该字段关联的对象时,所有相关的对象将被级联删除。例如,如果一个出版社对象被删除了,与该出版社相关联的所有图书对象也会被删除。models.SET_DEFAULT:(设置为默认值):当删除与该字段关联的对象时,该字段的值将设置为字段......