I am trying to read a file from a network share using the external jcifs library. Most sample codes I can find for reading files are quite complex, potentially unnecessarily so. I have found a simple way to write to a file as seen below. Is there a way to read a file using similar syntax?
SmbFile file= null;
try {
String url = "smb://"+serverAddress+"/"+sharename+"/TEST.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
file = new SmbFile(url, auth);
SmbFileOutputStream out= new SmbFileOutputStream(file);
out.write("test string".getBytes());
out.flush();
out.close();
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "ERROR: "+e);
}
SmbFile file = null;
byte[] buffer = new byte[1024];
try {
String url = "smb://"+serverAddress+"/"+sharename+"/TEST.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
file = new SmbFile(url, auth);
try (SmbFileInputStream in = new SmbFileInputStream(file)) {
int bytesRead = 0;
do {
bytesRead = in.read(buffer)
// here you have "bytesRead" in buffer array
}
while (bytesRead > 0);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "ERROR: "+e);
}
or even better, assuming that you're working with text files - using BufferedReader from Java SDK:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new SmbFileInputStream(file)))) {
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
}
}
And write with:
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new SmbFileOutputStream(file)))) {
String toWrite = "xxxxx";
writer.write(toWrite, 0, toWrite.length());
}
try {
String url = "smb://" + serverAddress + "/" + sharename + "/test.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(DOMAIN, USER_NAME, PASSWORD);
String fileContent = IOUtils.toString(new SmbFileInputStream(new SmbFile(url, auth)), StandardCharsets.UTF_8.name());
System.out.println(fileContent);
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
}
I could read some pdf files using this:
private final Singleton<CIFSContext> contextoDdetran = new Singleton<>() {
#Override
public CIFSContext inicializar() {
NtlmPasswordAuthenticator autenticador = new NtlmPasswordAuthenticator(smbDomain, smbUser, smbPassword);
return SingletonContext.getInstance().withCredentials(autenticador);
}
};
public byte[] readSmbFile(String fileName) {
try {
SmbFile file = new SmbFile(fileName, this.contextoDdetran.get());
return file.getInputStream().readAllBytes();
} catch(Exception e) {
final String msgErro = String.format("Error reading file '%s': %s", fileName, e.getMessage());
logger.error(msgErro, e);
throw new IllegalStateException(msgErro);
}
}
Related
Currently i am fetching a package details(Onnet Minutes, Offnet Minutes, etc) from a Json file "Data.json" from assets but i know we cannot change values from assets. So my Question is how to copy Data.json to internal storage and then Load it for read/Write.
I am using this to load Data.Json from Assets
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("Data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
Toast.makeText(jazz_sim_lagao_offer_details.this, "JSON Loaded", Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and using this code to update data
private void UpdateData() {
JSONObject JSONobj = null;
try {
loadJSONFromAsset();
//get JSONObject from JSON file
JSONobj = new JSONObject(loadJSONFromAsset());
//fetch JSONObject named
JSONObject Jazz_SimLagaoOffer = JSONobj.getJSONObject("packages").getJSONObject("jazz_packages").getJSONObject("call_packages").getJSONObject("sim_lagao_offer");
String Jazz_SimLagaoOffer_ONNET = Jazz_SimLagaoOffer.getString("onnet");
Jazz_SimLagaoOffer_OnNet_TextView.setText(Jazz_SimLagaoOffer_ONNET);
String Jazz_SimLagaoOffer_OFFNET = Jazz_SimLagaoOffer.getString("offnet");
Jazz_SimLagaoOffer_OffNet_TextView.setText(Jazz_SimLagaoOffer_OFFNET);
String Jazz_SimLagaoOffer_MBs = Jazz_SimLagaoOffer.getString("mbs");
Jazz_SimLagaoOffer_Mb_TextView.setText(Jazz_SimLagaoOffer_MBs);
String Jazz_SimLagaoOffer_SMS = Jazz_SimLagaoOffer.getString("sms");
Jazz_SimLagaoOffer_Sms_TextView.setText(Jazz_SimLagaoOffer_SMS);
String Jazz_SimLagaoOffer_SUBCODE = Jazz_SimLagaoOffer.getString("sub_code");
Jazz_SimLagaoOffer_Sub_Code_TextView.setText(Jazz_SimLagaoOffer_SUBCODE);
String Jazz_SimLagaoOffer_CHECKCODE = Jazz_SimLagaoOffer.getString("check_code");
Jazz_SimLagaoOffer_Check_Code_TextView.setText(Jazz_SimLagaoOffer_CHECKCODE);
String Jazz_SimLagaoOffer_UNSUBCODE = Jazz_SimLagaoOffer.getString("unsub_code");
Jazz_SimLagaoOffer_Unsub_Code_TextView.setText(Jazz_SimLagaoOffer_UNSUBCODE);
Jazz_SimLagaoOffer_Charges = Jazz_SimLagaoOffer.getString("charges");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), JSONobj + "", Toast.LENGTH_SHORT).show();
}
}
How to Get Json Object?
Here is My Data.Json
{
"packages" : {
"jazz_packages" : {
"call_packages" : {
"sim_lagao_offer" : {
"charges" : "0.01",
"check_code" : "*551*2#",
"mbs" : "1500",
"offnet" : "5000",
"onnet" : "3000",
"sms" : "3000",
"sub_code" : "*551#",
"unsub_code" : "*551*3#"
}
}
}
}
}
Try this
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(YOUR_ASSETS_FILE); // if files resides inside the "Files" directory itself
out = new FileOutputStream(STORAGE_PATH).toString() +"/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
e.printStackTrace();
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Use below code to read from storage
String jsongString = readFromFile();
JSONObject mainJsonObject = new JSONObject(jsongString);
JSONObject Jazz_SimLagaoOffer = mainJsonObject.getJSONObject("packages").getJSONObject("jazz_packages").getJSONObject("call_packages").getJSONObject("sim_lagao_offer");
Use below method to read data from internal storage file and return as String.
private String readFromFile() {
String ret = "";
InputStream inputStream = null;
try {
inputStream = openFileInput("names.json");
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(receiveString);
}
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
Hope this work :)
I Got Answer my own Question after 1 Day Research and Thanks to #pratik vekariya
helped me a lot.
CopyAssets() works perfect as defined #pratik vekariya in his answer and to readfromfile see my Question loadJSONFromAssets()
and i Just replaced line
InputStream is = getAssets().open("Data.json");
with this
InputStream is = new FileInputStream(getFilesDir().toString() +"/" + "Data.json");
to to load .json file from files and get json object from inputStrem
I have searched in stack and web a lot, for parsing a CSV file.
But I won't get what I want.
I have this table in CSV format,
what I want is, if I give the "ID"(which is 0,1,2,3... ) it should return me the value right to it i.e., if i give
"2" it should return me "hello how are you ?".
"4" it should return me "What do you prefer over tea ?"
How to achieve this?
Right now I kept my CSV file in the raw folder.
Any help will be apppreciated
You can save data in CSV as:-
ArrayList<TableData> arrayList=new ArrayList<>();
arrayList.add(new TableData(1,"Hello"));
arrayList.add(new TableData(2,"How are u"));
arrayList.add(new TableData(3,"I am fine"));
arrayList.add(new TableData(4,"Thank You"));
File file;
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File dir = new File (root.getAbsolutePath() + "/PersonData");
dir.mkdirs();
file = new File(dir, "Data.csv");
FileOutputStream out = null;
try {
// write to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
for (TableData element : arrayList) {
dos.writeUTF(String.valueOf(element.id));
dos.writeUTF(String.valueOf(element.name));
}
byte[] bytes = baos.toByteArray();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And Retrive it as:-
File file;
File root = Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/PersonData");
dir.mkdirs();
file = new File(dir, "Data.csv");
Uri u1 = null;
u1 = Uri.fromFile(file);
try {
FileInputStream inputStream=new FileInputStream(file);
String input="2";
String previousValue="";
ByteArrayInputStream bais = new ByteArrayInputStream(readFully(inputStream));
DataInputStream in = new DataInputStream(bais);
while (in.available() > 0) {
String element = in.readUTF();
if(previousValue.equalsIgnoreCase(input)){
textView.setText(element);
}
previousValue=element;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Method to convert inputStream to byte[]:-
public static byte[] readFully(InputStream input) throws IOException
{
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = input.read(buffer)) != -1)
{
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
}
Create a separate class for reading CSV file as:-
public class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream){
this.inputStream = inputStream;
}
public List read(){
List resultList = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
Now call this in your activity:-
String input="2";
InputStream inputStream = getResources().openRawResource(R.raw.sample);
CSVFile csvFile = new CSVFile(inputStream);
List scoreList = csvFile.read();
for(int i=0;i<scoreList.size();i++){
Object data_list=scoreList.get(i);
String a[]= (String[]) data_list;
String id=a[0];
String value=a[1];
if(input.equalsIgnoreCase(id)){
Log.d("TAG", "Value Found "+value);
}
}
I'm trying to create a Java application which can copy files from a Unix Samba share to a Windows folder. In order to achieve that, I'm using the JCIFS library.
I have the following code:
SmbFile smbFromFile = new SmbFile("smb:////192.168.10.1//data", auth);
smbFromFile.copyTo(destinationFolder);
I'm modifying it to:
SmbFile smbFromFile = new SmbFile("smb:////192.168.10.1//data", auth);
SmbFile destinationFolder = new SmbFile("C:\\Temp\\IN\\");
smbFromFile.copyTo(destinationFolder);
But it gives me the following error:
Exception in thread "main" jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password.
at jcifs.smb.SmbTransport.checkStatus(SmbTransport.java:546)
at jcifs.smb.SmbTransport.send(SmbTransport.java:663)
at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:390)
at jcifs.smb.SmbSession.send(SmbSession.java:218)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:176)
at jcifs.smb.SmbFile.doConnect(SmbFile.java:911)
at jcifs.smb.SmbFile.connect(SmbFile.java:957)
at jcifs.smb.SmbFile.connect0(SmbFile.java:880)
at jcifs.smb.SmbFile.copyTo(SmbFile.java:2303)
at RU.Tasks.Task3_Load_MedioSCP_Tekelek_file_To_DB_Oracle_BMCDB.main(Task3.java:203)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
If I try to create a new file on the Samba share, it works as expected:
String user = "usersamba";
String pass ="1234";
String hostname = "192.168.10.1";
String sharedFolder = "data/new";
String path = "smb://"+hostname+"/"+sharedFolder+"/test.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",user, pass);
SmbFile smbFile = new SmbFile(path,auth);
SmbFileOutputStream smbfos = new SmbFileOutputStream(smbFile);
smbfos.write("testing....and writing to a file".getBytes());
System.out.println("completed ...nice !");
Please help to resolve this problem.
option resolve to the problem
InputStream in = null;
OutputStream out = null;
try{
String SambaURL= "smb://usersamba:1234#192.168.1.110/data/1b.csv";
File destinationFolder = new File("C:\\Temp\\IN\\");
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS_");
File child = new File (destinationFolder+ "/" + fmt.format(new Date()) +"1b.csv");
SmbFile dir = new SmbFile(SambaURL);
SmbFile fileToGet=new SmbFile(SambaURL);
fileToGet.connect();
in = new BufferedInputStream(new SmbFileInputStream(fileToGet));
out = new BufferedOutputStream(new FileOutputStream(child));
byte[] buffer = new byte[4096];
int len = 0; //Read length
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
out.flush(); //The refresh buffer output stream
}
catch (Exception e) {
String msg = "The error occurred: " + e.getLocalizedMessage();
System.out.println(msg);
}
finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}
catch (Exception e) {}
}
source here
You need the proper auth mechanisms. See for example:
private static void GetFiles() throws IOException {
jcifs.Config.registerSmbURLHandler();
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
prop.getProperty("smbDomain"), prop.getProperty("smbUser"),
prop.getProperty("smbPass"));
StaticUserAuthenticator authS = new StaticUserAuthenticator(
prop.getProperty("smbDomain"), prop.getProperty("smbUser"),
prop.getProperty("smbPass"));
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts,
authS);
SmbFile smbFile = new SmbFile(prop.getProperty("smbURL"),auth);
FileSystemManager fs = VFS.getManager();
String[] files = smbFile.list();
for(String file:files) {
SmbFile remFile = new SmbFile(prop.getProperty("smbURL") + file, auth);
SmbFileInputStream smbfos = new SmbFileInputStream(remFile);
OutputStream out = new FileOutputStream(file);
byte[] b = new byte[8192];
int n;
while ((n = smbfos.read(b)) > 0) {
out.write(b, 0, n);
}
smbfos.close();
out.close();
}
}
I have looked around on how to do this and I keep finding different solutions, none of which has worked fine for me and I don't understand why. Does FileReader only work for local files? I tried a combination of scripts found on the site and it still doesn't quite work, it just throws an exception and leaves me with ERROR for the variable content. Here's the code I've been using unsuccessfully:
public String downloadfile(String link){
String content = "";
try {
URL url = new URL(link);
URLConnection conexion = url.openConnection();
conexion.connect();
InputStream is = url.openStream();
BufferedReader br = new BufferedReader( new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
content = sb.toString();
br.close();
is.close();
} catch (Exception e) {
content = "ERROR";
Log.e("ERROR DOWNLOADING",
"File not Found" + e.getMessage());
}
return content;
}
Use this as a downloader(provide a path to save your file(along with the extension) and the exact link of the text file)
public static void downloader(String fileName, String url) throws IOException {
File file = new File(fileName);
url = url.replace(" ", "%20");
URL website = new URL(url);
if (file.exists()) {
file.delete();
}
if (!file.exists()) {
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(fileName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
}
}
Then call this function to read the text file
public static String[] read(String fileName) {
String result[] = null;
Vector v = new Vector(10, 2);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String tmp = "";
while ((tmp = br.readLine()) != null) {
v.add(tmp);
}
Iterator i = v.iterator();
result = new String[v.toArray().length];
int count = 0;
while (i.hasNext()) {
result[count++] = i.next().toString();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return (result);
}
And then finally the main method
public static void main(){
downloader("D:\\file.txt","http://www.abcd.com/textFile.txt");
String data[]=read("D:\\file.txt");
}
try this:
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder();
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
sb.append(str );
}
in.close();
String serverTextAsString = sb.toString();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Good day!
I have just started developing for android. In my app, I need to copy the items in my assets folder to the internal storage.
I have searched a lot on SO including this which copies it to the external storage.
How to copy files from 'assets' folder to sdcard?
This is what I want to achieve:
I have a directory already present in the internal storage as X>Y>Z. I need a file to be copied to Y and another to Z.
Can anyone help me out with a code snippet? I really don't have any idea how to go on about this.
Sorry for my bad English.
Thanks a lot.
Use
String out= Environment.getExternalStorageDirectory().getAbsolutePath() + "/X/Y/Z/" ;
File outFile = new File(out, Filename);
After Editing in your ref. Link Answer.
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String outDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/X/Y/Z/" ;
File outFile = new File(outDir, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I did something like this. This allows you to copy all the directory structure to copy from Android AssetManager.
public String copyDirorfileFromAssetManager(String arg_assetDir, String arg_destinationDir) throws IOException
{
File sd_path = Environment.getExternalStorageDirectory();
String dest_dir_path = sd_path + addLeadingSlash(arg_destinationDir);
File dest_dir = new File(dest_dir_path);
createDir(dest_dir);
AssetManager asset_manager = getApplicationContext().getAssets();
String[] files = asset_manager.list(arg_assetDir);
for (int i = 0; i < files.length; i++)
{
String abs_asset_file_path = addTrailingSlash(arg_assetDir) + files[i];
String sub_files[] = asset_manager.list(abs_asset_file_path);
if (sub_files.length == 0)
{
// It is a file
String dest_file_path = addTrailingSlash(dest_dir_path) + files[i];
copyAssetFile(abs_asset_file_path, dest_file_path);
} else
{
// It is a sub directory
copyDirorfileFromAssetManager(abs_asset_file_path, addTrailingSlash(arg_destinationDir) + files[i]);
}
}
return dest_dir_path;
}
public void copyAssetFile(String assetFilePath, String destinationFilePath) throws IOException
{
InputStream in = getApplicationContext().getAssets().open(assetFilePath);
OutputStream out = new FileOutputStream(destinationFilePath);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
}
public String addTrailingSlash(String path)
{
if (path.charAt(path.length() - 1) != '/')
{
path += "/";
}
return path;
}
public String addLeadingSlash(String path)
{
if (path.charAt(0) != '/')
{
path = "/" + path;
}
return path;
}
public void createDir(File dir) throws IOException
{
if (dir.exists())
{
if (!dir.isDirectory())
{
throw new IOException("Can't create directory, a file is in the way");
}
} else
{
dir.mkdirs();
if (!dir.isDirectory())
{
throw new IOException("Unable to create directory");
}
}
}
try this below code
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
This is my Kotlin solution with auto-closable streams to copy in internal app storage:
val copiedFile = File(context.filesDir, "copied_file.txt")
context.assets.open("original_file.txt").use { input ->
copiedFile.outputStream().use { output ->
input.copyTo(output, 1024)
}
}
My small solution on Kotlin, for copy data from assets to INTERNAL STORAGE
fun copy() {
val bufferSize = 1024
val assetManager = context.assets
val assetFiles = assetManager.list("")
assetFiles.forEach {
val inputStream = assetManager.open(it)
val outputStream = FileOutputStream(File(context.filesDir, it))
try {
inputStream.copyTo(outputStream, bufferSize)
} finally {
inputStream.close()
outputStream.flush()
outputStream.close()
}
}
}
public void addFilesToSystem(String sysName, String intFil, Context c){
//sysName is the name of the file we have in the android os
//intFil is the name of the internal file
file = new File(path, sysName + ".txt");
if(!file.exists()){
path.mkdirs();
try {
AssetManager am = c.getAssets();
InputStream is = am.open(intFil);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
Toast t = Toast.makeText(c, "Making file: " + file.getName() + ". One time action", Toast.LENGTH_LONG);
t.show();
//Update files for the user to use
MediaScannerConnection.scanFile(c,
new String[] {file.toString()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// TODO Auto-generated method stub
}
});
} catch (IOException e) {
Toast t = Toast.makeText(c, "Error: " + e.toString() + ". One time action", Toast.LENGTH_LONG);
t.show();
e.printStackTrace();
}
}
}
To add a file, call the addFilesToSystem("this_file_is_in_the_public_system", "this_file_is_in_the_assets_folder", context/this context is if you do not have the method in the Activity/
Hope it helps
You can use the Envrionment#getDataDirectory method for that. It'll give the path of the data directory of the internal storage memory. This is generally where all the app related data is stored.
Alternately, if you want to store in the root directory, you can use the Environment#getRootDirectory method for that.
If you need to copy any file from assets to the internal storage and do it only once:
public void writeFileToStorage() {
Logger.d(TAG, ">> writeFileToStorage");
AssetManager assetManager = mContext.getAssets();
if (new File(getFilePath()).exists()) {
Logger.d(TAG, "File exists, do nothing");
Logger.d(TAG, "<< writeFileToStorage");
return;
}
try (InputStream input = assetManager.open(FILE_NAME);
OutputStream output = new FileOutputStream(getFilePath())) {
Logger.d(TAG, "File does not exist, write it");
byte[] buffer = new byte[input.available()];
int length;
while ((length = input.read(buffer)) != -1) {
output.write(buffer, 0, length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Logger.e(TAG, "File is not found");
} catch (IOException e) {
e.printStackTrace();
Logger.d(TAG, "Error while writing the file");
}
Logger.d(TAG, "<< writeFileToStorage");
}
public String getFilePath() {
String filePath = mContext.getFilesDir() + "/" + FILE_NAME;
Logger.d(TAG, "File path: " + filePath);
return filePath;
}