Read File From File Manager - java

I want to choose a file using the file chooser of android, then display its content in a EditText component.
I have this method where I open the file manager and search the file in Downloads
public void btnSearch(View view){
Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
fileIntent.setType("*/*");
fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(fileIntent,"Seleccione"),FILE_SELECTED_CODE);
} catch (android.content.ActivityNotFoundException ex){
System.out.println( ex.getMessage());
Toast.makeText(this,"Install a File Manager. ", Toast.LENGTH_SHORT).show();
}
}
And then I use this method to read the content of the file
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data == null)
return;
switch (requestCode){
case FILE_SELECTED_CODE:
if(resultCode == RESULT_OK){
Uri uri = data.getData();
String ruta = uri.getPath();
File archivo = new File(ruta);
try {
BufferedReader reader = new BufferedReader(new FileReader(archivo));
String linea = "";
String texto = "";
while((linea = reader.readLine()) != null){
texto += linea;
}
EditText tbxDatos = (EditText) findViewById(R.id.compDatos);
tbxDatos.setText(texto);
} catch(Exception e){
System.out.println( e.getMessage());
}
}
break;
}
super.onActivityResult(requestCode,resultCode,data);
}
But now I am having this exception when I select the file from the File Chooser:
Exception: /document/33 (No such file or directory)
Any ideas? Thank you.

Try this example Straight from the docs!!!
private String readTextFromUri(Uri uri) throws IOException {
InputStream inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
fileInputStream.close();
parcelFileDescriptor.close();
return stringBuilder.toString();
}

Related

Data management from file in Android

I am not able to save data from file into an object.If I recover the data from the file and save them in a string, the application works, but as soon as I try to save them inside an object (a Note object in my case), I fail .
It is a simple app(similar to notepads) with only a mainActivity to manage operations, an object class that include two variable, one for "title" and another one for "text" and an xml file with two input fields, two buttons(load and save) and a textView to view the data.
This is the the mainActivity code:
public class MainActivity extends AppCompatActivity {
EditText title,text;
Button save,load;
TextView result;
ArrayList<Note> notes = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = findViewById(R.id.id_title);
text = findViewById((R.id.id_post));
save = findViewById(R.id.buttonSave);
load = findViewById(R.id.buttonLoad);
result = findViewById(R.id.id_result);
Context context = getApplicationContext();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String titolo = title.getText().toString();
String post = text.getText().toString();
//Note nota = new Note(titolo,post);
Note nota = new Note(titolo,post);
//nota.setTitle(titolo);
//nota.setNote(post);
saveData(nota,context);
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//ArrayList<Note> data;
//String x;
//x= readData(context);
//x = data.getTitle() + " " +data.getNote();
//result.setText(x);
//setTextToTextview();
readData(context);
}
});
}
/**
* This function saves data on file
* #param nota
* #param context
*/
public void saveData(Note nota,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("text.txt", Context.MODE_APPEND));
outputStreamWriter.write(nota.getTitle().toString() + "," + nota.getNote().toString() + "\n");
outputStreamWriter.flush();
outputStreamWriter.close();
Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
e.getMessage();
}
}
private void setTextToTextview() {
String text = "";
for(int i = 0; i < notes.size(); i++)
{
text = text + notes.get(i).getTitle() + "" + notes.get(i).getNote() + "\n";
}
result.setText(text);
}
/**
* Read data from file
*/
public void readData(Context context) {
String stringa = "";
String part[];
//StringBuilder stringBuilder = new StringBuilder();
try
{
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ((receiveString = bufferedReader.readLine()) != null) {
StringTokenizer token = new StringTokenizer(receiveString, ",");
Note nota = new Note(token.nextToken(), token.nextToken());
notes.add(nota);
}
inputStream.close();
bufferedReader.close();
setTextToTextview();
//stringa = stringBuilder.toString();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
/*******************************************************
*this work
*******************************************************/
/*
public String readData(Context context)
{
String ret = "";
try {
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append("\n").append(receiveString);
}
inputStream.close();
bufferedReader.close();
ret = stringBuilder.toString();
}
} catch (IOException e) {
e.getMessage();
}
return ret;
}
*/
/*****************************************
* this work
*******************************************/
/*
public String readData(Context context)
{
// Note nota = new Note();
String stringa ="";
String ret = "";
try {
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append("\n").append(receiveString);
ret = stringBuilder.toString();
// StringTokenizer token = new StringTokenizer(ret,",");
String split[]= ret.split(",");
for(int i = 0; i< split.length;i++)
{
stringa = stringa +"," + split[i];
}
/*
nota.setTitle(split[0]);
nota.setNote(split[1]);
notes.add(nota);
*/
/*
}
inputStream.close();
bufferedReader.close();
//setTextToTextview();
//ret = stringBuilder.toString();
}
} catch (IOException e) {
e.getMessage();
}
return stringa;
}
*/
}
I also tried like this:
public void readData(Context context) {
String stringa = "";
String part[];
//StringBuilder stringBuilder = new StringBuilder();
try
{
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append("\n").append(receiveString);
stringa = stringBuilder.toString();
part = stringa.split(",",2);
Note nota = new Note(part[0],part[1]);
notes.add(nota);
setTextToTextview();
}
inputStream.close();
bufferedReader.close();
//stringa = stringBuilder.toString();
}
} catch (final IOException e) {
e.printStackTrace();
}
//return stringa;
}
thanks to anyone who can help me.

W/System.err: Error: /storage/emulated/0/2854: open failed: ENOENT (No such file or directory) JAVA

I am trying to open a file from the internal space of the device, but when I try to open it gives an ENOENT error.Trying to open a txt. file
have all permissions (read / write) in the manifest
public class MainActivity extends AppCompatActivity {
private static final int READ_REQUEST_CODE=42;
private static final int PERMISSION_REQUEST_STORAGE=1000;
private String readText(String input) {
StringBuilder str=new StringBuilder();
try {
File file=new File(input);
BufferedReader br=new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
str.append(line);
str.append("\n");
}
br.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
return str.toString();
}
private void performFileSearch(){
Intent intent=new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/*");
startActivityForResult(intent,READ_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==READ_REQUEST_CODE ){
if(data!=null){
Uri uri=data.getData();
String path=uri.getPath();
path=path.substring(path.indexOf(":")+1);
Toast.makeText(this,""+path,Toast.LENGTH_SHORT).show();
tv_output.setText(readText(path));
}
}
}
The problem is in API ,code is working only for v28 and lower.

PDF file getting corrupted and size increases when uploading it to FTP server | Android Studio | java

When I am uploading a pdf file to windows server it's getting corupted when downloading from FileZilla. The File size is also increasing in bytes.
Some files gets corrupted or some files only have half content.
Any help or code would be appreciated.
Thanks!
On Click to choose file from phone's directory:
btnSelectFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(Intent.createChooser(intent, "Select PDF File"), 21);
}
});
On Activity Result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 21:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
uri = data.getData();
uriString = uri.toString();
myFile = new File(uriString);
path = myFile.getAbsolutePath();
displayName = null;
file1 = Uri.fromFile(new File(path));
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
textFileSelectedOrNot.setText(displayName);
fileName = textFileSelectedOrNot.getText().toString();
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
textFileSelectedOrNot.setText(displayName);
fileName = textFileSelectedOrNot.getText().toString();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
Creating directory on server and uploading file:
class CreateDir extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String server = "XX.XXX.X.XX";
String username = "XXXXXXX";
String password = "XXXXX";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, 2102);
ftpClient.login(username, password);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
Log.d(TAG, "CONNECTED");
String dirPath = "/ws.gajeratrust.org/TestingApp/" + fileId + "/";
boolean created = ftpClient.makeDirectory(dirPath);
FTPUtils.mkdir(ftpClient, dirPath);
InputStream inputStream =getContentResolver().openInputStream(uri);
ftpClient.storeFile(dirPath+"/"+fileName,inputStream);
inputStream.close();
ftpClient.logout();
ftpClient.disconnect();
Log.d(TAG, "DISCONNECTED");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Please check the code any alterations or something I have coded wrong, please comment it.
InputStream inputStream = new FileInputStream(file);
Replace that by
InputStream inputStream = getContentResolver().openInputStream(data.getData());
You can throw away all code messing around with File and Cursor instances.
Also i wonder what those four lines before the line i quoted should do.
The problem was that I was setting the transfer mode incorrect way.
Right way is :
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);

AndroidStudio - save user info in CSV file and read it

I'm a newbie in programming on Android Studio. I'm trying to create a simple application to gain basic experience. In the application, I would need to store individual inputs to a file (ideally CSV) in internal memory. First of all, I am trying to save user data - my name and phone number. The save method looks like this:
public void save(View view)
{
String fileName = "user.csv";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), ContextWrapper.MODE_PRIVATE);
File file = new File(directory, fileName);
String data = "FirstName,LastName,PhoneNumber";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
The data seems to be saved and I'm redirected to MainActivity. Here is the method:
protected void onCreate(Bundle savedInstanceState) {
File file = new File(getFilesDir(),"user.csv");
if(!file.exists()) {
Intent intent = new Intent(this, activity_login.class);
startActivity(intent);
}
else {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv_name = findViewById(R.id.tv_name);
TextView tv_phone = findViewById(R.id.tv_phone);
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("user.csv"));
while ((sCurrentLine = br.readLine()) != null) {
tv_name.setText(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
No value is stored in TextView tv_name and the box is empty. Where am I making mistake?
Thank you very much for your help!
For reading data saved use this method uses, UTF_8 ENCODING
public static String readAsString(InputStream is) throws IOException {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
String line;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
reader = new BufferedReader(new InputStreamReader(is,UTF_8));
}
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
return sb.toString();
}
Use this method as follows, parsing file "user.csv".
public static String readFileAsString(File file) throws IOException {
return readAsString(new FileInputStream(file));
}
Fetch string and set textView
Use as this to read file:
FileInputStream fis = new FileInputStream("your full file path");
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
Below is the code for creating .csv file and inserting data into it.
For more look into my answer :https://stackoverflow.com/a/48643905/8448886
CODE HERE:
String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv
//by Hiting button csv will create inside phone storage.
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[]{"Country", "Capital"});
data.add(new String[]{"India", "New Delhi"});
data.add(new String[]{"United States", "Washington D.C"});
data.add(new String[]{"Germany", "Berlin"});
writer.writeAll(data); // data is adding to csv
writer.close();
callRead();
} catch (IOException e) {
e.printStackTrace();
}
}
});

How to remove specific line from the file

I am trying to delete a specific line from a file, but when I run this, it returns me all the files, deleted. More specific i have a favorite button at a video fragment and i want when user press it ,to write the title of video in file (already done) and when unpress it to delete it....
my.java class is:
private void writeToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/config.txt");
FileOutputStream fos = new FileOutputStream(file,true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (!file.exists()) {outputStreamWriter.write(g);}
outputStreamWriter.append("\n"+g +"\n");
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private void deleteToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
outputStreamWriter.write(text.toString());
}
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.favorite:
if(showingFirst==true) {
Context context = getActivity();
CharSequence text = "Added to Favorites";
int duration = Toast.LENGTH_SHORT;
item.setIcon(R.drawable.heart_off);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
writeToFile(title,context);
showingFirst=false;
} else {
Context context = getActivity();
CharSequence text = "Deleted from Favorites";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
deleteToFile(title,context);
item.setIcon(R.drawable.heart_wh);
showingFirst=true;
}
break;
case R.id.home:
Intent k=new Intent(getActivity(),MainActivity.class);
Log.i(TAG, "onNavigationItemSelected: ");
startActivity(k);
break;
}
return false;
}
So, problem lies at below line of codes where you are trying to open file for Read and Write simultaneously
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
Instead, I would suggest you to read your file completely and then at the end you should write to the file (overwrite).
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
//start writing from here
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
outputStreamWriter.write(text.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
}
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
This line:
FileOutputStream fos = new FileOutputStream(file);
resets contents of the file (ie replaces it with empty file). I recommend you add logging and/or debug your code so you will have a better understanding of what is going on.

Categories

Resources