【问题标题】:Android Create/Write File in Internal StorageAndroid 在内部存储中创建/写入文件
【发布时间】:2015-08-27 18:56:54
【问题描述】:

我一直在寻找如何创建一个文件,然后在内部存储中写入它几天,但找不到任何有效或我能理解的东西。我以前从来没有做过这样的事情,所以我很迷茫。

根据android开发者网站页面,这段代码如果不存在应该创建一个文件夹,但是当我调用它时,它给了我一个错误。如果这意味着什么,该类将扩展 SurfaceView。

public GameView(Context context) {
    super(context);

    gameLoopThread = new GameLoopThread(this);
    holder = getHolder();
    holder.addCallback(new Callback() {

        public void surfaceDestroyed(SurfaceHolder holder) {
            System.exit(1);
        }

        public void surfaceCreated(SurfaceHolder holder) {
            gameLoopThread.setRunning(true);
            gameLoopThread.start();
        }

        public void surfaceChanged(SurfaceHolder holder, int format,
                int width, int height) {

        }

    });

    createFile();

}

public void createFile() {
    String FILENAME = "hello_file";
    String string = "hello world!";

    FileOutputStream fos;
    try {
        fos = getContext().openFileOutput(FILENAME,Context.MODE_PRIVATE);
        fos.write(string.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我最终想要做的就是在内部存储中创建一个文件,将一个整数(我的玩家在游戏中的得分)保存到该文件,然后能够加载并保存它。

谢谢。

【问题讨论】:

  • 您是否收到错误消息?你能贴一下你的logcat吗?
  • 如果你想实现持久键值对,我建议Android's SharedPreferences
  • 抱歉,耽误了一点时间。 "08-27 15:10:46.005: E/Trace(737): error opening trace file: No such file or directory (2)",
  • 错误描述中没有提到文件名吗?使用 'context' 参数而不是 'getContext()'。
  • '此代码如果不存在,则应创建一个文件夹,'。不,它会创建一个文件。如果它已经存在,则删除它。

标签: android internal-storage


【解决方案1】:

如果您想实现持久键值对,我建议Android's SharedPreferences。使用SharedPreferences 很简单:

final SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); //MY_PREFS_NAME could  be something useful, like username, so your data can be easily separated.

final static SCORE = "score"; //This variable simply holds the string "score", so we can tell the SharedPreferences which data we'd like.
int getScore() {
    return prefs.getInt(SCORE, 0); // second argument is default value if there is no value for key.
}

void setScore(int score) {
    Editor editor = prefs.edit();
    editor.putInt(SCORE, score);
    editor.commit();
}

这些设置将在您的应用程序的多次运行中保持不变。

【讨论】:

  • 嗯,我看看我能想出什么。
【解决方案2】:

这就是我在本地写入和读取照片文件的方式。可以应用类似的过程来处理不同类型的文件。只需使用不同的文件扩展名和不同的方法返回数据类型。

// Creates an ImageFile
private File createNewPhotoFile() throws IOException {

    String imageFileName = "JPEG";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();

    image.createNewFile();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    FileOutputStream fo = new FileOutputStream(image);
    fo.write(stream.toByteArray());
    fo.close();

    return image;
}

// Retrieve and convert from file to Bitmap
private Bitmap retrieveImageFromFile(ImageView target, File fileForPath) {

    // Get the dimensions of the View
    int targetW = target.getWidth();
    int targetH = target.getHeight();

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(fileForPath.getAbsolutePath(), bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = 4; //Math.min(photoW / targetW, photoH / targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;

    Bitmap bitmap = BitmapFactory.decodeFile(newPhotoFile.getAbsolutePath(), bmOptions);

    return bitmap;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多