I Downloaded both jars from http://www.siegmann.nl/epublib/android
but the sample code does not create a file
in my sdcard or internal storage
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import nl.siegmann.epublib.domain.Author;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.epub.EpubWriter;
import android.app.Activity;
import android.os.Bundle;
public class EpubAppActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Book b = new Book();
b.getMetadata().addTitle("test epub book");
b.getMetadata().addAuthor(new Author("author name"));
EpubWriter w = new EpubWriter();
FileOutputStream fos;
try {
File file = new File(getApplicationContext().getExternalFilesDir(null), "test.epub");
if(!file.exists()){
file.createNewFile();
}
fos = new FileOutputStream(file);
w.write(b, fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
not get error however I can not find the file (it is not created)
I forgot to add
<uses-permission android: name = "android.permission.WRITE_EXTERNAL_STORAGE" />
in Android Manifest
Related
Here's a code of MainActivity.java to save a file named filename.txt in App's Internal Storage, which is working fine.
package com.bla.smthing;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am able to see the file by File Explorer of Android Studio. How can I save the file in a directory say files/Somefolder/otherfolderchild/filename.txt?
Currently, it is saving as files/filename.txt
Do I need to create additional parent file directories for that?
Try this it might help you. For the above marshmallow version please check the write permissions.
public void saveToExternalStorage() {
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/directoryName";
try
{
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(fullPath, "fileName.txt");
if(file.exists())
file.delete();
file.createNewFile();
fOut = new FileOutputStream(file);
fOut.flush();
fOut.close();
}
catch (Exception e)
{
Log.e("saveToExternalStorage()", e.getMessage());
}
}
I am trying to open a CSV file downloaded into internal storage for reading purpose alone. This is the code I have used:
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import java.io.FileInputStream;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
try {
String FileName = "/storage/emulated/0/Download/MyDocument.csv";
FileInputStream fis = openFileInput(FileName);
fis.read();
fis.close();
Toast.makeText(getBaseContext(),"File Access Permitted",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(),"File Access Denied",Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
While the file is downloaded and I am able to open it in File Manager, the above code does not work. How do I achieve the required functionality?
As per this stackoverflow question's accepted answer, you could try this:
public String readFileFromDownloads(String fileName) {
File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if (!downloadsDir.exists()) return null;
File file = new File(downloadsDir, fileName);
if (!file.exists()) return null;
try {
StringBuilder fileContent = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
fileContent.append(line);
fileContent.append('\n');
}
br.close();
return fileContent.toString();
} catch (IOException ex) {
//Handle error
return null;
}
}
And then call readFileFromDownloads("MyDocument.csv"); from inside your onClick(); method.
Also, you might need to add android.permission.READ_EXTERNAL_STORAGE to your Manifest and handle Android 6.0 new permission system as per Android Docs.
I have written simple code to save data into text files internally. But, after running the code, I don't know where I can find the required file. Additionally, I find an error message in the log cast as
"SPAN_EXCLUSIVE_EXCLUSIVE"
package com.example.saving_files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
File file;
FileOutputStream fos;
String FlieName = "output.text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
file = new File(FlieName);
try {
fos = openFileOutput(FlieName, MODE_PRIVATE);
fos.write(122);
} catch (FileNotFoundException e) {
Log.d("output", file.getAbsolutePath());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
file = getFilesDir();
Log.d("output_path", file.getAbsolutePath());
}
}
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard, "filename");
FileOutputStream f = new FileOutputStream(file);
This code will create new file in the root directory of your SD. Dont forget to add
<uses-permission> to write to SD in your manifest
Check this code and comments;
File sdcard = Environment.getExternalStorageDirectory();
File f = new File(sdcard, "/yourfile");
if (!f.exsist()) {
f.createNewFile();
// Use outwriter here, (outputstream) search how to write into a text file in java code
}
Can I change the contrast of an image from the byte stream of the Image? I have done necessary to do copying the image and I need to add the change contrast part to the code.
Any idea how to do this? Or is it even possible?
package make.image.bw;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class MakeImageBWActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // set screen view
String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath() +"/earthglobe.jpg";
RandomAccessFile file = null;
try {
file = new RandomAccessFile(imageInSD, "r");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
File myFile = new File(Environment.getExternalStorageDirectory(), "latestearth.jpg");
byte[] buffer = new byte[1024];
try {
FileOutputStream out = new FileOutputStream(myFile);
while(file.read(buffer)!=-1){
out.write(buffer,0,1024);
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("tag", "finished");
finish();
}
}
Thanking You in advance for your valuable suggestions.
You should try to look at that Google IO 2012 session : Doing More With Less: Being a Good Android Citizen
There is a good demo of image manipulation with RenderScript at 22min30.
The code of the presentation can be found here
here is my entire code (ps Im a noobie);
package xom.aaa.aaa;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FilewritertestActivity extends Activity {
TextView textout1, textout2, textout3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) findViewById(R.id.button1);
textout1 = (TextView) findViewById(R.id.textView1);
textout2 = (TextView) findViewById(R.id.textView2);
textout3 = (TextView) findViewById(R.id.textView3);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//--------- OutputStreamWriter ------------
try {
FileOutputStreamfOut=openFileOutput("settings1.dat", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write( "using fileoutput stream to write this to a file");
osw.flush();
osw.close();
}catch(Exception e){
e.printStackTrace(System.err);
}
String datax = "";
StringBuffer buffer = new StringBuffer();
//--------- InputStreamReader -------------------
try {
FileInputStream fIn = openFileInput("settings1.dat");
Reader reader = new InputStreamReader(fIn);
int data = reader.read(); // reads the next char
while(data != -1){
buffer.append((char)data);
data = reader.read();
}
reader.close();
} catch ( Exception e) {
e.printStackTrace();
}
textout1.setText( buffer.toString());
//--------------- FileWriter ---------------
try {
FileWriter fw = new FileWriter("settings1.dat");
BufferedWriter out = new BufferedWriter(fw);
//BufferedWriter out = new BufferedWriter(new FileWriter("settings1.dat"));
out.write("a String");
out.close();
} catch (Exception e){
e.printStackTrace();
textout2.setText(e.toString());
}
}
});
}
}
Problem is FileWriter Not working ( for file "settings1.dat")
but OutputStreamWriter and InputStreamReader does work ( for file "settings1.dat")
the code shows writing then reading to file "settings1.dat" Is ok with Stream Witer/Reader...
But FileWriter code get error message Filenotfoundexception "read-only file system"
So why does one technique work on the same File and the other doesn´t
Can you please tell what Iam missing -- thanks Trevor
I'm guessing your problem is you just aren't getting an IOException. You could try changing
catch(IOException e)
to
catch(Exception e)
This will then catch all exceptions which extend the Exception object (it will not catch Errors though). However, I don't have the tools to test out your code so you will have to try it out yourself and post the results.
Best of luck.