Hey Guys, Today I am going to share the important code of Assets. How to open the file and read the file from assets folder. In that Scenario, There is a class in Android API Asset Manager.
Open file with AssetManager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| package app.test; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.StringTokenizer; import android.app.Activity; import android.content.res.AssetManager; import android.os.Bundle; import android.widget.TextView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); TextView tv = new TextView( this ); setContentView(tv); try { AssetManager manager = getAssets(); InputStream mInput = manager.open( "data.csv" ); byte[] data = new byte[128]; mInput.read(data); mInput.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
Read Asset Files
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| package app.test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.content.res.AssetManager; import android.os.Bundle; import android.widget.TextView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); TextView textView = new TextView( this ); setContentView(textView); AssetManager assetManager = getAssets(); InputStream inputStream = null ; try { inputStream = assetManager.open( "/text.txt" ); String text = loadTextFile(inputStream); textView.setText(text); } catch (IOException e) { textView.setText( "Couldn't load file" ); } finally { if (inputStream != null ) try { inputStream.close(); } catch (IOException e) { textView.setText( "Couldn't close file" ); } } } public String loadTextFile(InputStream inputStream) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] bytes = new byte[4096]; int len = 0; while ((len = inputStream.read(bytes)) > 0) byteStream.write(bytes, 0, len); return new String(byteStream.toByteArray(), "UTF8" ); } } |
No comments:
Post a Comment