gpt4 book ai didi

Android 文件 I/O openFileInput() 未定义

转载 作者:太空宇宙 更新时间:2023-11-03 11:44:13 24 4
gpt4 key购买 nike

            package com.example.tictactoeshowgrid;

import android.os.Bundle;
import java.io.*;
import android.widget.Toast;
import android.content.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.content.Context;

public class ImportOBJ {

protected void onCreate(String filename) {
try
{
FileInputStream fis = openFileInput(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null, input="";
while ((line = reader.readLine()) != null)
input += line;
reader.close();
fis.close();
//toast("File successfully loaded.");
//return input;
}
catch (Exception ex)
{
//toast("Error loading file: " + ex.getLocalizedMessage());
//return "";
}
}
}

我正在查看 Android 的文件 I/O 示例。我想知道为什么 openFileInput 会出现错误,因为它是一个未定义的函数。我在想,也许我错过了进口?如果不是,那么一定有其他问题。

提前致谢...

最佳答案

要在非 Activity 类中访问 openFileInput 方法,您需要通过使用参数化方法发送 Context 或使用 ImportOBJ 类构造函数将 Activity Context 传递给它:

protected void onCreate(String filename,Context context) {
try
{
FileInputStream fis = context.openFileInput(filename);
//...your code here...
}
catch (Exception ex)
{

}
}

并从您的 Activity 传递上下文为:

ImportOBJ obj_import=new ImportOBJ();
obj_import.onCreate(<File_Name_Here>,Your_Current_Activity_Name.this);

关于Android 文件 I/O openFileInput() 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17439682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com