gpt4 book ai didi

java - 创建一个单独的方法来从 Assets 文件夹中的子文件夹中读取文本文件

转载 作者:行者123 更新时间:2023-11-30 11:48:36 25 4
gpt4 key购买 nike

这是我第一次来这里,所以我有点紧张,如果我似乎不太清楚我在问什么,请原谅我。

问题是,我试图使用我在单独的类中创建的方法从 assets 文件夹的子文件夹中读取文件。我已经研究了几天,但我无法在任何地方找到解决方案,所以我来到这里作为最后的手段。我需要将文件读取方法分开,因为还有其他 View /Activity 将使用完全相同的方法,我认为为每个 Activity 继续复制和粘贴相同的代码是不明智的。好的,这是我到目前为止所做的:

public class ReadAssets extends Activity {


public void read(Context context, String filepath, int textviewid) {

try {
InputStream input = getAssets().open(filepath);

int size = input.available();

// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
input.read(buffer);
input.close();

// Convert the buffer into a string.
String text = new String(buffer);

// Finally insert the string into the text view.
TextView tv = (TextView) findViewById(textviewid);
tv.setText(text);

} catch (IOException e) {
// Throws an exception if an error is found
throw new RuntimeException(e);
}


}
}

我想将此方法放入的 Activity :

public class GeneralSetupActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gettingstarted_layout);


ReadAssets nA = new ReadAssets();
nA.read(this,"gettingstarted/GettingStarted.txt", R.id.displayTextView);

// try {
// InputStream input =getAssets().open("gettingstarted/GettingStarted.txt");
//
// int size = input.available();
//
// // Read the entire asset into a local byte buffer.
// byte[] buffer = new byte[size];
// input.read(buffer);
// input.close();
//
// // Convert the buffer into a string.
// String text = new String(buffer);
//
// // Finally insert the string into the text view.
// TextView tv = (TextView) findViewById(R.id.displayTextView);
// tv.setText(text);
//
// } catch (IOException e) {
// // Throws an exception if an error is found
// throw new RuntimeException(e);
// }
}

}

如果有人能为我指明正确的方向,我将不胜感激。我也希望我没有占便宜,但我想知道如何一个接一个地导入和显示一系列文本文件。

干杯伙计们,谢谢:)

最佳答案

如果您需要所有不同类型的 Activity 都可以使用此方法,您应该考虑将该方法放在父类(super class)中,以便所有子级都可以使用它。

public class ExtraFunctionalActivity extends Activity
{
public void read(...)
{
//your code
}
}

public class GeneralSetupUtility extends ExtraFunctionalActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.gettingstarted_layout);

read(this,"gettingstarted/GettingStarted.txt", R.id.displayTextView);

}
}

否则,如果一堆不相关的类需要这个方法,你可以把它放在一个实用类中;

public class FileUtil
{

public static void read(...)
{
//your code
}

}

然后你可以在需要的地方调用它

FileUtil.read(args here);

关于java - 创建一个单独的方法来从 Assets 文件夹中的子文件夹中读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8707069/

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