Java 创建一个单独的方法以从“资源”文件夹中的子文件夹读入文本文件
这是我第一次来这里,所以我有点紧张,请原谅我,如果我似乎不完全清楚我在问什么 问题是,我试图使用在单独类中创建的方法从assets文件夹的子文件夹中读取文件。我已经研究了几天,但是我在任何地方都找不到解决方案,所以我来这里是最后的选择。我需要将文件读取方法分开,因为其他视图/活动将使用完全相同的方法,我不认为为每个活动复制和粘贴相同的代码是明智的。好的,以下是我到目前为止所做的:Java 创建一个单独的方法以从“资源”文件夹中的子文件夹读入文本文件,java,android,file,methods,assets,Java,Android,File,Methods,Assets,这是我第一次来这里,所以我有点紧张,请原谅我,如果我似乎不完全清楚我在问什么 问题是,我试图使用在单独类中创建的方法从assets文件夹的子文件夹中读取文件。我已经研究了几天,但是我在任何地方都找不到解决方案,所以我来这里是最后的选择。我需要将文件读取方法分开,因为其他视图/活动将使用完全相同的方法,我不认为为每个活动复制和粘贴相同的代码是明智的。好的,以下是我到目前为止所做的: public class ReadAssets extends Activity { public void r
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);
}
}
}
我想将此方法放在其中的活动:
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);
// }
}
}
如果有人能给我指出正确的方向,我将不胜感激。我也希望我没有利用这个机会,但我想知道如何一个接一个地导入和显示一系列文本文件
干杯,伙计们,
谢谢:)您可能有一个类似FileParSingulity的类,其中包含要分离的方法。您可以将Inputstream定义为参数(您可以将其他必需的内容作为该方法的参数传递)。无论您想使用这个方法做什么,都要实例化上面的类,并通过传递参数来调用这个方法 Fileparinsgutility util=newfileparsingutility();
Returnobj retObj=util.parse(……) < P>如果你需要对所有不同类型的活动都可用,你应该考虑把方法放在一个超类中,以便所有的孩子都能使用它。
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);
非常感谢。正如你所说,我创建了一个超级类。谢谢:D