Reputation: 5
I want to read from txt file and send to TextView. My method works on Java Project I read and I see System.out.print but the same method doesnt work in MainActivity. How can I fixed.Thanks
MainActivity
public class MainActivity extends Activity {
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.textView1);
Parsing p =new Parsing();
try {
String gelen=p.readTxt();
txt.setText(gelen);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Parsing:
public class Parsing {
public String readTxt() throws FileNotFoundException
{
File file = new File("C:\\Users\\John\\Desktop\\try.txt");
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
}
I'm working it but I see just TextView
.
Upvotes: 0
Views: 137
Reputation: 3177
First of all Android Application Project is different from Java Project.
You can not use File file = new File("C:\\Users\\John\\Desktop\\try.txt");
in android.
Place your text file in the /assets directory under the Android project. Use AssetManager
class to access it.
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
If you are going to access file from memory card, Then use inputsteram is
in your program. Also you need the following permission to read the text file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Upvotes: 0
Reputation: 12042
you cannot specify the computer directory
files to the android file path location to read lines in it.
assests
and change the
path and then try.Upvotes: 3
Reputation: 81
How can I read a text file in Android?
I don't mean to be rude but try to search first. This question with similar problem was already asked.
I hope this link will help you.
Cheers
Upvotes: 1
Reputation: 8281
You must put the file in the asset
folder of your project.
Then to access it you can do something like
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
for more details read my answer here :
Upvotes: 0
Reputation: 444
For file on sdcard ("sdcard\myfolder\1.txt") please use:
File file = new File(Environment.getExternalStorageDirectory(), "myfolder\1.txt");
Also dont forget:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Upvotes: 0