B4A Library File handling library

A file handling library that includes support for rooted devices. MLfiles will use superuser as well as busybox or toolbox if they are installed. The correct system paths are automatically searched for available superuser packages.

Attached is my file handling library for access to the Android file system. It includes a more complete Samba implementation for remote file access to windows or other samba servers. Below is a list of methods and variables available in the library. There is a simple example app in the zip to demonstrate some of the functions. works on rooted or non rooted devices.

MLfiles is now Version 1.50. MLsmb is now Version 1.51. See the attachments at the end of this post.

From version 1.50 MLfiles and MLsmb are separate libraries. If you are using both in your project, you'll need to check both libraries in the IDE. The jcifs samba library routines add over 300k to the size of an app. By separating the 2 libraries you get to choose when or if to use the samba library (MLsmb) or not.

MLfiles
Author:
Jem Miller - Missing Link Software
Version: 1.5
  • MLfiles
    Fields:
    • ErrStr As String
      The StdErr interface used by most commands. This should
      contain any error message from the OS.
    • FSerror As String
      The value of stderror is set to this string after each call
      if it is empty, there was no error.
    • HaveBB As Boolean
      True if busybox is installed.
    • HaveRoot As Boolean
      True if GetRoot succeeds.
    • HaveTB As Boolean
      True if toolbox is installed.
    • OutStr As String
      The StdOut interface returned by some commands. This
      will contain what would normally be text output to a linux
      terminal.
    • fsStdOut As String
      Contains the Linux StdOut result of a command. This is
      what you would see in a Linux console if the command
      is successful.
    Methods:
    • Escape (fname As String) As String
      Escapes spaces, "(" and ")" characters in a filename
      returns the original string if already escaped.
    • Exists (Filename As String) As Boolean
      Checks to see if a file exists.
      Filename is the path and filename string
      Returns True on success
    • GetDiskstats (Path As String) As String
      Returns information of the given partition or pathname as a string formatted as
      Size Used Free Blocksize
      each field is separated with a single space.
      For example:
      B4X:
      Dim fs as MLFiles
      Dim tmp as String
      tmp = fs.GetDiskstats("/mnt/sdcard")
      In the example above, tmp Might return :
      8G 57M 8G 4096
      If busybox is present, the output will be in bytes for each field.
      Uses Root if available.
    • GetExtSd As String
      Returns the location of the external SD card mount point.
      This is a best guess based upon the standards being adopted in later releases of Android.
      Returns an empty string if not found.
    • GetFileDate (Fname As String) As Long
      Gets the last modified date and time of a file or directory.
      Returns the timestamp in milliseconds.
    • GetFileExt (FName As String) As String
      Returns the file extension (if available) of the file FName
      otherwise returns the entire path and filename sent
    • GetFileType (Fname As String) As String
      Gets the filetype of Fname.
      Returns file type as a String on success or Unknown on failure.
      Returns standard mime types such as:

      text/plain
      audio/mpeg
      text/XML
      image/jpeg

      as file types
    • GetFreespace (Path As String) As Long
      Returns the available space of the given partition/disk as a Long
      Path is the mount point or directory within a partition
      Note that some partitions are protected and will not return a value.
    • GetGigsFree (Path As String) As Double
      Returns the available space of the given partition/disk in gigabytes
      Path is the partition path or directory within a partition
      Returns the available space on the partition containing the Path in gigabytes.
      Note that some partitions are protected and will not return a value.
    • GetPerms (fname As String) As String
      Example:
      perms = GetPerms(filename)
      Returns a Linux style permission string "rwxrwxrwx" rwx for each of owner, group, and others.
      Use - for no permission, like "rw-r--r--" for owner read write, group read, and others read.
      Works with files or directories.
    • GetRoot
      Attempts to gain root access.
      Sets HaveRoot to True on success
    • GetSymlink (Fname As String) As String
      Gets the target of a symbolic link in string format.
    • IsReadable (Fname As String) As Boolean
      Returns True if file or directory is readable to this user process.
    • IsWritable (Fname As String) As Boolean
      Returns True if file or directory is writable to this user process.
    • ReadTxtFile (Fname As String) As String
      Reads a text file and returns its contents in a StringBuilder.
      Uses Root if available.
    • RootCmd (Command As String, Args As String, StdOut As StringBuilder, StdErr As StringBuilder, useBB As Boolean) As Boolean
      Executes a system command or program through the root adapter.
      Uses standard permissions if root is not available.
      Command - the command to execute
      Args - the arguments to the command
      StdOut - the text that would appear in a linux console
      StdErr - any error text returned by the command
      useBB - use busybox for the command if available
      Returns true on success.
    • Sdcard As String
      Returns the path to the external SD card if present as a string including the ending /
      like /mnt/sdcard/
      returns an empty string if not present
    • SdcardReady As String
      Returns a state string for the external sdcard.

      mounted = mounted and ready
      unmounted = card present but unmounted
      bad removal = sdcard removed without closing
      removed = no card present
      nofs = unformatted or unknown filesystem
      shared = mount point is currently shared with usb device
      unmountable = sdcard is present but damaged
      checking = media is being scanned
      mounted read only = sdcard is not writable
    • SetFileDate (Fname As String, Time As Long) As Boolean
      Sets file date and time on Fname to Time in milliseconds.
      Returns True on success.
    • Symlink (Linkname As String, Filename As String) As Boolean
      Creates the symbolic link Linkname from Filename as in Linux/Unix.
      Works on files or directories.
      Returns True on success.

      Uses Root if available.
    • Touch (Fname As String) As Boolean
      Creates an empty file with the current date and time.
      Fname is the name of the file to create. If the file exists the datestamp is changed to NOW.
      Returns True on success.
      Uses root if available.
    • WriteTxtFile (Fname As String, Txt As String) As Boolean
      Writes the contents of Txt to the file Fname.
      Fname must already exist or a FileNotFound exception is thrown.
      Uses root if available.
    • chmod (Filename As String, permissions As String) As Boolean
      Sets file permissions for a file or directory. Requires correct user access or root.
      Permissions are as Linux chmod numeric value.
      1 = execute
      2 = write
      4 = read

      644 = owner read/write (4 + 2), group read, other read
      755 = owner read/write/execute (4 + 2 + 1), group read/execute, other read,execute

      Uses Root if available.
    • cp (Src As String, Dest As String) As Boolean
      Copy a file from Src to Dest
      Returns True on success.
      Uses Root if available.
    • cpr (Src As String, Dest As String) As Boolean
      Recursive copy just like the Linux cp -r
      Copies all files and directories under the Src path to Dest.
      Works with directories, but is meaningless for files.
      Returns True on success.
      Uses Root if available.
    • createZipFile (path As String)
      Creates a backup zip of the directory path
    • dirEntries (Dir As String, Hidden As Boolean) As ArrayList
      Returns a list of formatted directory entries or an empty list on failure. As in :
      d---rwxr-x system sdcard_rw 0 2011-11-13 12:59 LOST.DIR
      Each element is in the form of a space separated string of
      permissions and type (drwxr-xr-x) where the first char indicates a directory, link, or regular file (d, l, or -).
      owner name
      group name
      file size
      date
      time
      file name
      Hidden is a boolean and will show ALL files hidden or not if True.
      Note that this method makes every attempt to fill in a size for symlinks and directories
      This means that you should always get 7 fields.
      Uses Root if available.
    • extractZipFiles (zip_file As String, directory As String)
      Unzips a backup zipfile to directory.
      Creates the destination DIR if needed.
    • extractZipFilesFromDir (zipName As String, fromDir As String, toDir As String)
      Unzips zipName from fromDir to toDir
    • isDir (Path As String) As Boolean
      Returns true if Path is a directory
    • isSymlink (Fname As String) As Boolean
      Returns True if file or directory is a symbolic link.
    • mkdir (Dir As String) As Boolean
      Make a directory and any needed parent directories
      Returns True on success
      Uses Root if available.
    • mv (Oldname As String, Newname As String) As Boolean
      Use to move or rename files or directories from Oldname to Newname.
      Returns True on success.
      Uses Root if available.
    • rm (Fname As String) As Boolean
      Remove (delete) a file or directory
      Directories must be empty
      Returns True on success.
      Uses Root if available.
    • rmrf (Fname As String) As Boolean
      Remove (delete) a directory recursively.
      ALL files and sub-directories will be deleted, EMPTY OR NOT.
      Returns True on success.
      Uses Root if available.
    • zipPeek (zipname As String) As ArrayList
      Opens a zip file and returns the list of its contents
      in a list.
      zipname is the full path and filename to be displayed
      Returns a formatted string of :
      path/Name, compressed FileSize, and DateTime as a single semicolon separated string
    Permissions:
    • android.permission.WRITE_EXTERNAL_STORAGE

The MLsmb library:

MLsmb
Author:
Jem Miller - Missing Link Software
Version: 1.51
  • MLsmb
    Events:
    • Success (Name as String As , Size as Long As )
    Fields:
    • FSerror As String
    Methods:
    • Escape (fname As String) As String
      Escapes spaces, "(" and ")" characters in a filename
      Returns the original string if already escaped.
    • Initialize
      Initializes internal variables
    • SmbCopy (FromFile As String, ToFile As String, eventname As String)
      Copies a file TO or FROM the Samba server, including samba to samba copying.
      Calls the Success event when completed.

      The event contains the filename and file size as:

      varname_Success(Name as String, Size as Long)

      put any code you need to execute on successful copy in the event sub.
      eventname_Success(Name As String, Size As Long)
    • SmbCredentials (Username As String, Password As String, Domain As String)
      Set the user name, password, and domain for a samba server.
      If set, this record will be passed to the server when the Smb methods are called.
    • SmbDelete (Url As String, SmbFile As String) As Boolean
      Deletes a file on the Samba server
      Returns True on success.
    • SmbIP (host As String) As String
      Returns the IP address of the Samba server
    • SmbList (SmbUrl As String, Pattern As String) As ArrayList
      Returns a list of SmbFile types on the samba server.
      Check the FSerror string to see if authentication failed or is needed.
      SmbUrl = the SMB path to list
      Pattern = an optional wildcard search pattern
    • SmbMove (From As String, To As String) As Boolean
      Moves or renames files or directories on the Samba server
      Returns True on success.
    • mkSmbDirs (Dir As String) As Boolean
      Makes a directory on the Samba server.
      This method will create any missing elements of the new path.
      Returns True on success.
    • smbInStream (Afile As String) As InputStream
      Creates an input stream from the file Afile that can be fed to another object.
      Returns null if not successful.
    Permissions:
    • android.permission.INTERNET
    • android.permission.WRITE_EXTERNAL_STORAGE
  • SambaFile
    Fields:
    • TYPE_COMM As Int
    • TYPE_FILESYSTEM As Int
    • TYPE_NAMED_PIPE As Int
    • TYPE_PRINTER As Int
    • TYPE_SERVER As Int
    • TYPE_SHARE As Int
    • TYPE_WORKGROUP As Int
    Methods:
    • CanRead As Boolean
      True is the file or directory is readable.
    • CanWrite As Boolean
      True if the directory or file can be written to.
    • DiskFree As Long
      Returns the free space of this Samba share.
    • GetPath As String
      Returns the SMB path to this file or directory
    • GetServer As String
      Returns the Smaba server name
    • GetShare As String
      Returns the share name
    • GetType As Int
      Returns an Int representing the type of SMB object for this SambaFile from 0 through 6
      TYPE_FILESYSTEM, a regular file or directory
      TYPE_WORKGROUP, A workgroup
      TYPE_SERVER, a Samba server
      TYPE_SHARE, a shared directory
      TYPE_PRINTER, a shared printer
      TYPE_NAMED_PIPE, a named pipe
      TYPE_COMM, a communications device
    • IsFile As Boolean
      True if this is a file and not a directory.
    • IsHidden As Boolean
      True if this file or directory is hidden.
    • IsInitialized As Boolean
    • LastModified As Long
      Returns the modify date of this file
    • Name As String
      Returns the file name
    • Parent As String
      Returns the parent directory
    • ServerIp (Server As String) As String
      Returns the IP address of the server
    • Size As Long
      Returns the file size
    • isDir As Boolean
      Ckecks if this file is a directory.

The jcifs.jar file used in this library is available HERE

There are 2 test projects included in the zip file. One for MLfiles and one for MLsmb.


Version 1.1
  • Many small changes have been made for efficiency. The GetRoot has been modified to try different methods of determining if a device has root access available. I added the Escape method in both the files and Samba objects to escape file names containing spaces, "(" and ")" characters. It returns the original string with no changes if nothing needs to be done, otherwise it escapes those characters with the "\" character so that linux and cifs can use the string.

    Version 1.2
    Added 2 new methods and changed 1.

    Added GetGigsFree(String Path) This returns the freespace of a partition in gigabytes as a double

    Added GetFreespace(String Path) This returns the freespace of a partition in bytes as a Long

    Changed GetDiskFree(String Path) to GetDiskstats(String Path) It still returns a formatted STRING of values.

    Updated the libtest.b4a project.

    Version 1.3
    Removed unused parameter from GetFreespace to avoid any confusion.

    Version 1.4
    Changed OS calls to look for busybox by default. Samsung and others do not offer common OS calls in their ROMs, but (at least in Samsungs case) they include busybox on the device, which solves this problem.

    Version 1.41
    Changed the cp and cpr methods. If the cp command is not present on the OS version, both use native methods to copy the file or do a recursive copy of the directory tree. These methods do not honor root access, so normal permissions are used.

    Version 1.42
    Minor change to the GetGigsFree and GetFreespace methods to try to ensure they return accurate results.

    Version 1.43
    Actually made version 1.42 changes work. About time! :)

    Version 1.44
    Added the Exists method to test if a file or directory exists.

    Version 1.45
    Fixes some zip extraction weirdness. NOTE: The order of fromDir and toDir have been changed! Also the destination directory will now be created if needed in both ExtractFilesFromDir() and ExtractFiles.

    Version 1.47
    Added GetExtSd method to find a mounted external (add-on_ sd card. Lots or rewrites and optimizations. The Samba routines are mostly rewritten and are now very reliable. Better authentication in all samba methods as well. More error correction and detection.

    Version 1.50
    Separated the local files and smb files into 2 libraries.
MLsmb Version 1.51
Corrected headers that got changed during the library separation process. Attached MLsmb-1.51.zip to correct this issue.

.
 

Attachments

  • MLFiles-1.50.zip
    42.4 KB · Views: 1,195
  • MLsmb-1.51.zip
    19.1 KB · Views: 886
Last edited:

HotShoe

Well-Known Member
Licensed User
Longtime User
Hi,

can I use this lib to copy an edited version of the build.prop to /system/?

I am having a bit of trouble doing this via code. The device is rooted as e.g. romtoolboxlite can be used to edit /system/build.prop manually and that saves just fine..

But if I use code like

busybox cp /mnt/sdcard/whatever.txt /system/build.prop

I get ''read only file system'' returned :-(

Thanks,

Eric

/system is mounted as read only by default. you'll need to remount it as rw to write to it.


hello ,

same error here, i tried all sort of combinations , but the lib reference to MLsmb does not show up (though it is there in IDE Tab)

could you see into this?

regards

There has to be something going on with so many reporting it. I will look into this later today.

Thanks,

--- Jem
 

HotShoe

Well-Known Member
Licensed User
Longtime User
Well, you guys are right, MLsmb was broken. I use a file server to keep my projects and library source. That way I don't have to guess which machine has the latest version of a project/app/library, etc. Unfortunately, I did the separation of the libraries on a laptop and the version on the file server was a "work in progress" and not the finished version.

Please get the MLsmb-1.51.zip file attached to the first post and let me know if it still acts strange.

Thanks,

--- Jem
 

sanjibnanda

Active Member
Licensed User
Longtime User
Well, you guys are right, MLsmb was broken. I use a file server to keep my projects and library source. That way I don't have to guess which machine has the latest version of a project/app/library, etc. Unfortunately, I did the separation of the libraries on a laptop and the version on the file server was a "work in progress" and not the finished version.

Please get the MLsmb-1.51.zip file attached to the first post and let me know if it still acts strange.

Thanks,

--- Jem
Thanks ... works now.
 

tpakis

Active Member
Licensed User
Longtime User
Hello Jem, I am trying to run the sample smbtst, but i get "error listing smb://". The library and jcifs file are properly installed, any idea what's wrong?
 

HotShoe

Well-Known Member
Licensed User
Longtime User
Hello Jem, I am trying to run the sample smbtst, but i get "error listing smb://". The library and jcifs file are properly installed, any idea what's wrong?

Is Wifi is turned on and connected to your router ok?
 

HotShoe

Well-Known Member
Licensed User
Longtime User
2 or 3 others have reported this in the past, and I still don't know why a few can't get an smb link. It may have to do with router configuration or something in the code that I just can't see. In all of the other cases the b4a smb library works, so for now, I suggest you stick with that until I can find a reason for the failure and a solution. I have been through the SMB library and don't see anything structurally different in there than I am doing.

Thanks,

--- Jem
 

johndb

Active Member
Licensed User
Longtime User
Update on Samsung and other devices

Well it seems update 1.40 will NOT solve the problem of copying files and directories. I was told that Samsung includes busybox, but it and others use the standard toolbox utility (so does the emulator), but that utility does not include the cp command. It is simple to copy files in Linux (android) without the cp command for rooted or non rooted devices. Copying directories is much more complicated though.

I have existing routines in both C and Pascal to do recursive copying, but it is not a simple set of commands that I can add in a few minutes. This adds considerable size to the library, but is the cleanest way. I have fixed the single file copy routine for the next release, but the recursive copy will have to wait for a while.

--- Jem

Has this library been updated to allow the following on Samsung devices?
  • cpr (Src As String, Dest As String) As Boolean
    Recursive copy just like the Linux cp -r
    Copies all files and directories under the Src path to Dest.
    Works with directories, but is meaningless for files.
    Returns True on success.
    Uses Root if available.
  • rmrf (Fname As String) As Boolean
    Remove (delete) a directory recursively.
    ALL files and sub-directories will be deleted, EMPTY OR NOT.
    Returns True on success.
    Uses Root if available.

Thanks,

John
 

koaunglay

Member
Licensed User
Longtime User
A file handling library that includes support for rooted devices. MLfiles will use superuser as well as busybox or toolbox if they are installed. The correct system paths are automatically searched for available superuser packages.

Attached is my file handling library for access to the Android file system. It includes a more complete Samba implementation for remote file access to windows or other samba servers. Below is a list of methods and variables available in the library. There is a simple example app in the zip to demonstrate some of the functions. works on rooted or non rooted devices.

MLfiles is now Version 1.50. MLsmb is now Version 1.51. See the attachments at the end of this post.

From version 1.50 MLfiles and MLsmb are separate libraries. If you are using both in your project, you'll need to check both libraries in the IDE. The jcifs samba library routines add over 300k to the size of an app. By separating the 2 libraries you get to choose when or if to use the samba library (MLsmb) or not.

MLfiles
Author:
Jem Miller - Missing Link Software
Version: 1.5
  • MLfiles
    Fields:
    • ErrStr As String
      The StdErr interface used by most commands. This should
      contain any error message from the OS.
    • FSerror As String
      The value of stderror is set to this string after each call
      if it is empty, there was no error.
    • HaveBB As Boolean
      True if busybox is installed.
    • HaveRoot As Boolean
      True if GetRoot succeeds.
    • HaveTB As Boolean
      True if toolbox is installed.
    • OutStr As String
      The StdOut interface returned by some commands. This
      will contain what would normally be text output to a linux
      terminal.
    • fsStdOut As String
      Contains the Linux StdOut result of a command. This is
      what you would see in a Linux console if the command
      is successful.
    Methods:
    • Escape (fname As String) As String
      Escapes spaces, "(" and ")" characters in a filename
      returns the original string if already escaped.
    • Exists (Filename As String) As Boolean
      Checks to see if a file exists.
      Filename is the path and filename string
      Returns True on success
    • GetDiskstats (Path As String) As String
      Returns information of the given partition or pathname as a string formatted as
      Size Used Free Blocksize
      each field is separated with a single space.
      For example:
      B4X:
      Dim fs as MLFiles
      Dim tmp as String
      tmp = fs.GetDiskstats("/mnt/sdcard")
      In the example above, tmp Might return :
      8G 57M 8G 4096
      If busybox is present, the output will be in bytes for each field.
      Uses Root if available.
    • GetExtSd As String
      Returns the location of the external SD card mount point.
      This is a best guess based upon the standards being adopted in later releases of Android.
      Returns an empty string if not found.
    • GetFileDate (Fname As String) As Long
      Gets the last modified date and time of a file or directory.
      Returns the timestamp in milliseconds.
    • GetFileExt (FName As String) As String
      Returns the file extension (if available) of the file FName
      otherwise returns the entire path and filename sent
    • GetFileType (Fname As String) As String
      Gets the filetype of Fname.
      Returns file type as a String on success or Unknown on failure.
      Returns standard mime types such as:

      text/plain
      audio/mpeg
      text/XML
      image/jpeg

      as file types
    • GetFreespace (Path As String) As Long
      Returns the available space of the given partition/disk as a Long
      Path is the mount point or directory within a partition
      Note that some partitions are protected and will not return a value.
    • GetGigsFree (Path As String) As Double
      Returns the available space of the given partition/disk in gigabytes
      Path is the partition path or directory within a partition
      Returns the available space on the partition containing the Path in gigabytes.
      Note that some partitions are protected and will not return a value.
    • GetPerms (fname As String) As String
      Example:
      perms = GetPerms(filename)
      Returns a Linux style permission string "rwxrwxrwx" rwx for each of owner, group, and others.
      Use - for no permission, like "rw-r--r--" for owner read write, group read, and others read.
      Works with files or directories.
    • GetRoot
      Attempts to gain root access.
      Sets HaveRoot to True on success
    • GetSymlink (Fname As String) As String
      Gets the target of a symbolic link in string format.
    • IsReadable (Fname As String) As Boolean
      Returns True if file or directory is readable to this user process.
    • IsWritable (Fname As String) As Boolean
      Returns True if file or directory is writable to this user process.
    • ReadTxtFile (Fname As String) As String
      Reads a text file and returns its contents in a StringBuilder.
      Uses Root if available.
    • RootCmd (Command As String, Args As String, StdOut As StringBuilder, StdErr As StringBuilder, useBB As Boolean) As Boolean
      Executes a system command or program through the root adapter.
      Uses standard permissions if root is not available.
      Command - the command to execute
      Args - the arguments to the command
      StdOut - the text that would appear in a linux console
      StdErr - any error text returned by the command
      useBB - use busybox for the command if available
      Returns true on success.
    • Sdcard As String
      Returns the path to the external SD card if present as a string including the ending /
      like /mnt/sdcard/
      returns an empty string if not present
    • SdcardReady As String
      Returns a state string for the external sdcard.

      mounted = mounted and ready
      unmounted = card present but unmounted
      bad removal = sdcard removed without closing
      removed = no card present
      nofs = unformatted or unknown filesystem
      shared = mount point is currently shared with usb device
      unmountable = sdcard is present but damaged
      checking = media is being scanned
      mounted read only = sdcard is not writable
    • SetFileDate (Fname As String, Time As Long) As Boolean
      Sets file date and time on Fname to Time in milliseconds.
      Returns True on success.
    • Symlink (Linkname As String, Filename As String) As Boolean
      Creates the symbolic link Linkname from Filename as in Linux/Unix.
      Works on files or directories.
      Returns True on success.

      Uses Root if available.
    • Touch (Fname As String) As Boolean
      Creates an empty file with the current date and time.
      Fname is the name of the file to create. If the file exists the datestamp is changed to NOW.
      Returns True on success.
      Uses root if available.
    • WriteTxtFile (Fname As String, Txt As String) As Boolean
      Writes the contents of Txt to the file Fname.
      Fname must already exist or a FileNotFound exception is thrown.
      Uses root if available.
    • chmod (Filename As String, permissions As String) As Boolean
      Sets file permissions for a file or directory. Requires correct user access or root.
      Permissions are as Linux chmod numeric value.
      1 = execute
      2 = write
      4 = read

      644 = owner read/write (4 + 2), group read, other read
      755 = owner read/write/execute (4 + 2 + 1), group read/execute, other read,execute

      Uses Root if available.
    • cp (Src As String, Dest As String) As Boolean
      Copy a file from Src to Dest
      Returns True on success.
      Uses Root if available.
    • cpr (Src As String, Dest As String) As Boolean
      Recursive copy just like the Linux cp -r
      Copies all files and directories under the Src path to Dest.
      Works with directories, but is meaningless for files.
      Returns True on success.
      Uses Root if available.
    • createZipFile (path As String)
      Creates a backup zip of the directory path
    • dirEntries (Dir As String, Hidden As Boolean) As ArrayList
      Returns a list of formatted directory entries or an empty list on failure. As in :
      d---rwxr-x system sdcard_rw 0 2011-11-13 12:59 LOST.DIR
      Each element is in the form of a space separated string of
      permissions and type (drwxr-xr-x) where the first char indicates a directory, link, or regular file (d, l, or -).
      owner name
      group name
      file size
      date
      time
      file name
      Hidden is a boolean and will show ALL files hidden or not if True.
      Note that this method makes every attempt to fill in a size for symlinks and directories
      This means that you should always get 7 fields.
      Uses Root if available.
    • extractZipFiles (zip_file As String, directory As String)
      Unzips a backup zipfile to directory.
      Creates the destination DIR if needed.
    • extractZipFilesFromDir (zipName As String, fromDir As String, toDir As String)
      Unzips zipName from fromDir to toDir
    • isDir (Path As String) As Boolean
      Returns true if Path is a directory
    • isSymlink (Fname As String) As Boolean
      Returns True if file or directory is a symbolic link.
    • mkdir (Dir As String) As Boolean
      Make a directory and any needed parent directories
      Returns True on success
      Uses Root if available.
    • mv (Oldname As String, Newname As String) As Boolean
      Use to move or rename files or directories from Oldname to Newname.
      Returns True on success.
      Uses Root if available.
    • rm (Fname As String) As Boolean
      Remove (delete) a file or directory
      Directories must be empty
      Returns True on success.
      Uses Root if available.
    • rmrf (Fname As String) As Boolean
      Remove (delete) a directory recursively.
      ALL files and sub-directories will be deleted, EMPTY OR NOT.
      Returns True on success.
      Uses Root if available.
    • zipPeek (zipname As String) As ArrayList
      Opens a zip file and returns the list of its contents
      in a list.
      zipname is the full path and filename to be displayed
      Returns a formatted string of :
      path/Name, compressed FileSize, and DateTime as a single semicolon separated string
    Permissions:
    • android.permission.WRITE_EXTERNAL_STORAGE

The MLsmb library:

MLsmb
Author:
Jem Miller - Missing Link Software
Version: 1.51
  • MLsmb
    Events:
    • Success (Name as String As , Size as Long As )
    Fields:
    • FSerror As String
    Methods:
    • Escape (fname As String) As String
      Escapes spaces, "(" and ")" characters in a filename
      Returns the original string if already escaped.
    • Initialize
      Initializes internal variables
    • SmbCopy (FromFile As String, ToFile As String, eventname As String)
      Copies a file TO or FROM the Samba server, including samba to samba copying.
      Calls the Success event when completed.

      The event contains the filename and file size as:

      varname_Success(Name as String, Size as Long)

      put any code you need to execute on successful copy in the event sub.
      eventname_Success(Name As String, Size As Long)
    • SmbCredentials (Username As String, Password As String, Domain As String)
      Set the user name, password, and domain for a samba server.
      If set, this record will be passed to the server when the Smb methods are called.
    • SmbDelete (Url As String, SmbFile As String) As Boolean
      Deletes a file on the Samba server
      Returns True on success.
    • SmbIP (host As String) As String
      Returns the IP address of the Samba server
    • SmbList (SmbUrl As String, Pattern As String) As ArrayList
      Returns a list of SmbFile types on the samba server.
      Check the FSerror string to see if authentication failed or is needed.
      SmbUrl = the SMB path to list
      Pattern = an optional wildcard search pattern
    • SmbMove (From As String, To As String) As Boolean
      Moves or renames files or directories on the Samba server
      Returns True on success.
    • mkSmbDirs (Dir As String) As Boolean
      Makes a directory on the Samba server.
      This method will create any missing elements of the new path.
      Returns True on success.
    • smbInStream (Afile As String) As InputStream
      Creates an input stream from the file Afile that can be fed to another object.
      Returns null if not successful.
    Permissions:
    • android.permission.INTERNET
    • android.permission.WRITE_EXTERNAL_STORAGE
  • SambaFile
    Fields:
    • TYPE_COMM As Int
    • TYPE_FILESYSTEM As Int
    • TYPE_NAMED_PIPE As Int
    • TYPE_PRINTER As Int
    • TYPE_SERVER As Int
    • TYPE_SHARE As Int
    • TYPE_WORKGROUP As Int
    Methods:
    • CanRead As Boolean
      True is the file or directory is readable.
    • CanWrite As Boolean
      True if the directory or file can be written to.
    • DiskFree As Long
      Returns the free space of this Samba share.
    • GetPath As String
      Returns the SMB path to this file or directory
    • GetServer As String
      Returns the Smaba server name
    • GetShare As String
      Returns the share name
    • GetType As Int
      Returns an Int representing the type of SMB object for this SambaFile from 0 through 6
      TYPE_FILESYSTEM, a regular file or directory
      TYPE_WORKGROUP, A workgroup
      TYPE_SERVER, a Samba server
      TYPE_SHARE, a shared directory
      TYPE_PRINTER, a shared printer
      TYPE_NAMED_PIPE, a named pipe
      TYPE_COMM, a communications device
    • IsFile As Boolean
      True if this is a file and not a directory.
    • IsHidden As Boolean
      True if this file or directory is hidden.
    • IsInitialized As Boolean
    • LastModified As Long
      Returns the modify date of this file
    • Name As String
      Returns the file name
    • Parent As String
      Returns the parent directory
    • ServerIp (Server As String) As String
      Returns the IP address of the server
    • Size As Long
      Returns the file size
    • isDir As Boolean
      Ckecks if this file is a directory.

The jcifs.jar file used in this library is available HERE

There are 2 test projects included in the zip file. One for MLfiles and one for MLsmb.


Version 1.1
  • Many small changes have been made for efficiency. The GetRoot has been modified to try different methods of determining if a device has root access available. I added the Escape method in both the files and Samba objects to escape file names containing spaces, "(" and ")" characters. It returns the original string with no changes if nothing needs to be done, otherwise it escapes those characters with the "\" character so that linux and cifs can use the string.

    Version 1.2
    Added 2 new methods and changed 1.

    Added GetGigsFree(String Path) This returns the freespace of a partition in gigabytes as a double

    Added GetFreespace(String Path) This returns the freespace of a partition in bytes as a Long

    Changed GetDiskFree(String Path) to GetDiskstats(String Path) It still returns a formatted STRING of values.

    Updated the libtest.b4a project.

    Version 1.3
    Removed unused parameter from GetFreespace to avoid any confusion.

    Version 1.4
    Changed OS calls to look for busybox by default. Samsung and others do not offer common OS calls in their ROMs, but (at least in Samsungs case) they include busybox on the device, which solves this problem.

    Version 1.41
    Changed the cp and cpr methods. If the cp command is not present on the OS version, both use native methods to copy the file or do a recursive copy of the directory tree. These methods do not honor root access, so normal permissions are used.

    Version 1.42
    Minor change to the GetGigsFree and GetFreespace methods to try to ensure they return accurate results.

    Version 1.43
    Actually made version 1.42 changes work. About time! :)

    Version 1.44
    Added the Exists method to test if a file or directory exists.

    Version 1.45
    Fixes some zip extraction weirdness. NOTE: The order of fromDir and toDir have been changed! Also the destination directory will now be created if needed in both ExtractFilesFromDir() and ExtractFiles.

    Version 1.47
    Added GetExtSd method to find a mounted external (add-on_ sd card. Lots or rewrites and optimizations. The Samba routines are mostly rewritten and are now very reliable. Better authentication in all samba methods as well. More error correction and detection.

    Version 1.50
    Separated the local files and smb files into 2 libraries.
MLsmb Version 1.51
Corrected headers that got changed during the library separation process. Attached MLsmb-1.51.zip to correct this issue.

.
Please help my error!
B4X:
** Activity (main) Create, isFirst = true **
java.lang.IllegalArgumentException: Invalid path:             900.0M   590.4M   309.6M   4096
    at android.os.StatFs.doStat(StatFs.java:46)
    at android.os.StatFs.<init>(StatFs.java:39)
    at MLfiles.Fileslib.MLfiles.GetGigsFree(MLfiles.java:623)
    at org.mlsoft.test.main._test(main.java:418)
    at org.mlsoft.test.main._activity_create(main.java:325)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:187)
    at org.mlsoft.test.main.afterFirstLayout(main.java:100)
    at org.mlsoft.test.main.access$100(main.java:17)
    at org.mlsoft.test.main$WaitForLayout.run(main.java:78)
    at android.os.Handler.handleCallback(Handler.java:730)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5457)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: libcore.io.ErrnoException: statfs failed: ENOENT (No such file or directory)
    at libcore.io.Posix.statfs(Native Method)
    at libcore.io.ForwardingOs.statfs(ForwardingOs.java:131)
    at android.os.StatFs.doStat(StatFs.java:44)
    ... 19 more
java.lang.IllegalArgumentException: Invalid path:             900.0M   590.4M   309.6M   4096
2.png
 

koaunglay

Member
Licensed User
Longtime User
I want to make my parth!
B4X:
        Dim dsize As Double
        sd = fs.GetDiskstats("/data/user/0")    '    com.netqin.ps/databases/nqrecords.db
            If sd <> "" Then
                Msgbox("You have an external mounted at:" &sd, "Information")
'                        folderS = sd
'                        If File.Exists(folderS, "") = False Then
'                            ToastMessageShow("Not found!!!!!!", False)
'                            Return
'                        End If
'
            Else
                Msgbox("Not found anthing!!", "Information")
            End If
                   
       
        tmp1 = fs.SdcardReady
       
        If tmp1 <> "mounted" Then
            Msgbox("No usable found!", "Error")
            Activity.Finish
        End If
            dsize = Round2(fs.GetGigsFree(sd), 2)
           
            Msgbox("You have " & dsize & " available on sdcard", "Information")
           
        sd = fs.Sdcard
        tmp = sd & "MLtest/"
       
        ok = fs.mkdir(tmp)       
        ok = fs.Touch(tmp& "Test")
            If ok Then
                ok = fs.cp(tmp & "Test", tmp & "reText")
            End If
           
        fs.mkdir("/data/user/0/tst")
        ok = fs.cpr(tmp, "/data/user/0/tst")
       
        fs.GetRoot
        ok = fs.HaveRoot
        tmp1 = fs.fsStdOut
        If ok Then
            Msgbox("OK! Found Root Access!", "Info")
        Else
            Msgbox("No Root Access.", "Info")
        End If
'=====================

   
    filelis = fs.dirEntries(tmp)    '    fs.dirEntries(sd)    ' File.ListFiles(folderS)
    For i = 0 To filelis.Size -1
        DoEvents
'        Dim userInterfaceFile As String
'        userInterfaceFile = filelis.Get(i)
        lV.AddSingleLine(filelis.Get(i))
    Next
But I can't go on. There is some error in your sample zip for me. My English is not good. I mean..https://www.b4x.com/android/forum/threads/file-handling-library.19247/page-6#post-354002
 

koaunglay

Member
Licensed User
Longtime User
When I update MLfile v1.50 I get this error!
B4X:
** Activity (main) Create, isFirst = true **
java.lang.IllegalArgumentException: Invalid path: Filesystem               Size     Used     Free   Blksize
/mnt/sdcard            900.0M   590.4M   309.6M   4096
    at android.os.StatFs.doStat(StatFs.java:46)
    at android.os.StatFs.<init>(StatFs.java:39)
    at MLfiles.Fileslib.MLfiles.GetGigsFree(MLfiles.java:630)
    at org.mlsoft.test.main._test(main.java:418)
    at org.mlsoft.test.main._activity_create(main.java:325)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:187)
    at org.mlsoft.test.main.afterFirstLayout(main.java:100)
    at org.mlsoft.test.main.access$100(main.java:17)
    at org.mlsoft.test.main$WaitForLayout.run(main.java:78)
    at android.os.Handler.handleCallback(Handler.java:730)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5457)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: libcore.io.ErrnoException: statfs failed: ENOENT (No such file or directory)
    at libcore.io.Posix.statfs(Native Method)
    at libcore.io.ForwardingOs.statfs(ForwardingOs.java:131)
    at android.os.StatFs.doStat(StatFs.java:44)
    ... 19 more
java.lang.IllegalArgumentException: Invalid path: Filesystem               Size     Used     Free   Blksize
/mnt/sdcard            900.0M   590.4M   309.6M   4096
 

HotShoe

Well-Known Member
Licensed User
Longtime User
B4X:
sd = fs.GetDiskstats("/data/user/0")    '    com.netqin.ps/databases/nqrecords.db
            If sd <> "" Then
                Msgbox("You have an external mounted at:" &sd, "Information")
'                        folderS = sd
'                        If File.Exists(folderS, "") = False Then
'                            ToastMessageShow("Not found!!!!!!", False)
'                            Return
'                        End If
'
            Else
                Msgbox("Not found anthing!!", "Information")
            End If

From the error message it looks like you are running the code above while those lines are not commented out. In this case sd will be the return string from the getDiskStats call and cannot be used as an argument for the call to File.Exists (not a valid path). In the error, that string would equal:
Filesystem Size Used Free Blksize
/mnt/sdcard 900.0M 590.4M 309.6M 4096

Also be aware that /data is a protected path in android, so unless the device is rooted, you won't be able to read files or create a directory in that path.

--- Jem
 

koaunglay

Member
Licensed User
Longtime User
From the error message it looks like you are running the code above while those lines are not commented out. In this case sd will be the return string from the getDiskStats call and cannot be used as an argument for the call to File.Exists (not a valid path). In the error, that string would equal:
Filesystem Size Used Free Blksize
/mnt/sdcard 900.0M 590.4M 309.6M 4096

Also be aware that /data is a protected path in android, so unless the device is rooted, you won't be able to read files or create a directory in that path.

--- Jem
Thanks for your reply! I get the same error when I run your sample file /mnt/sdcard
 

koaunglay

Member
Licensed User
Longtime User
From the error message it looks like you are running the code above while those lines are not commented out. In this case sd will be the return string from the getDiskStats call and cannot be used as an argument for the call to File.Exists (not a valid path). In the error, that string would equal:
Filesystem Size Used Free Blksize
/mnt/sdcard 900.0M 590.4M 309.6M 4096

Also be aware that /data is a protected path in android, so unless the device is rooted, you won't be able to read files or create a directory in that path.

--- Jem
Thanks! The error from in log is running your sample file.
 

HotShoe

Well-Known Member
Licensed User
Longtime User
Actually, your sample above calls GetDiskStats as its first call, where the sample does not. It should look like this:

B4X:
Sub  test
   Dim dt As Long
   Dim ok As Boolean
   Dim l As List
   Dim arr, sd As String
   Dim i As Int
   Dim dsize As Double
   
   sd = fs.GetExtSd 'see if there is an external sdcard (internal cards are partitioned to make part look like an external card)
   
   If sd <> "" Then
   Msgbox("You have an external SD card mounted at: "&sd,"Information")
   Else
   Msgbox("I found no external SD card mounted","Information")
   End If
   
   tmp1 = fs.SdcardReady ' check the status of the card
   
   If tmp1 <> "mounted" Then  ' see if the card is usable
   Msgbox("No usable external sdcard found!","Error")
   Activity.Finish
   End If
   
   dsize = Round2(fs.getgigsfree(sd),2)
   
   Msgbox("You have " & dsize & " gigabytes available on your SD card","Information")
   
   sd = fs.Sdcard
   
   tmp = sd & "MLtest/" 'sdcard returns the path with a trailing /
   
   'Zip extraction test. Create and add a test.zip to your files to use this
'   File.Copy(File.DirAssets,"test.zip",sd,"test.zip")
'   
'   tmp1 = sd&"zipdir"
'   fs.extractZipFilesFromDir("test.zip", sd, tmp1)
   
   ok = fs.mkdir(tmp) ' make a new directory
   
   ok = fs.touch(tmp & "Test") 'create an empty file (or change the file access time/date to NOW if it exists)
   
   If ok Then
   ok = fs.cp(tmp & "Test", tmp & "reTest") ' copy the file
   End If
   
   fs.mkdir("/mnt/sdcard/tst") 'make a dir
   
   ok = fs.cpr(tmp,"/mnt/sdcard/tst") 'copy all files to the new dir
   
   fs.GetRoot ' see if we have root access
   ok = fs.HaveRoot
   
   tmp1 = fs.fsStdOut

   If ok Then
   Msgbox("I have Root access!","Information")
   Else
   Msgbox("I do not have Root access.","Information")
   End If
   
   l = fs.dirEntries(tmp, True) ' get file list of the new directory
   
   For i = 0 To l.Size - 1
   ListView1.AddSingleLine(l.Get(i))
   Next
   
   DoEvents
   
   l.Clear
   
   l = sf.SmbList("smb://",Null) 'get a list of all samba groups
   
   For i = 0 To l.Size - 1
   ListView2.AddSingleLine(l.Get(i))
   Next
   
   DoEvents
   
   tmp1 = fs.Escape("c:\Program Files (x86)") 'test the escape method (available in samba as well)
   Log(tmp1)
   
End Sub

--- Jem
 

koaunglay

Member
Licensed User
Longtime User
Actuy, your sample above calls GetDiskStats as its first call, where the sample does not. It should look like this:

B4X:
Sub  test
   Dim dt As Long
   Dim ok As Boolean
   Dim l As List
   Dim arr, sd As String
   Dim i As Int
   Dim dsize As Double
  
   sd = fs.GetExtSd 'see if there is an external sdcard (internal cards are partitioned to make part look like an external card)
  
   If sd <> "" Then
   Msgbox("You have an external SD card mounted at: "&sd,"Information")
   Else
   Msgbox("I found no external SD card mounted","Information")
   End If
  
   tmp1 = fs.SdcardReady ' check the status of the card
  
   If tmp1 <> "mounted" Then  ' see if the card is usable
   Msgbox("No usable external sdcard found!","Error")
   Activity.Finish
   End If
  
   dsize = Round2(fs.getgigsfree(sd),2)
  
   Msgbox("You have " & dsize & " gigabytes available on your SD card","Information")
  
   sd = fs.Sdcard
  
   tmp = sd & "MLtest/" 'sdcard returns the path with a trailing /
  
   'Zip extraction test. Create and add a test.zip to your files to use this
'   File.Copy(File.DirAssets,"test.zip",sd,"test.zip")
'  
'   tmp1 = sd&"zipdir"
'   fs.extractZipFilesFromDir("test.zip", sd, tmp1)
  
   ok = fs.mkdir(tmp) ' make a new directory
  
   ok = fs.touch(tmp & "Test") 'create an empty file (or change the file access time/date to NOW if it exists)
  
   If ok Then
   ok = fs.cp(tmp & "Test", tmp & "reTest") ' copy the file
   End If
  
   fs.mkdir("/mnt/sdcard/tst") 'make a dir
  
   ok = fs.cpr(tmp,"/mnt/sdcard/tst") 'copy all files to the new dir
  
   fs.GetRoot ' see if we have root access
   ok = fs.HaveRoot
  
   tmp1 = fs.fsStdOut

   If ok Then
   Msgbox("I have Root access!","Information")
   Else
   Msgbox("I do not have Root access.","Information")
   End If
  
   l = fs.dirEntries(tmp, True) ' get file list of the new directory
  
   For i = 0 To l.Size - 1
   ListView1.AddSingleLine(l.Get(i))
   Next
  
   DoEvents
  
   l.Clear
  
   l = sf.SmbList("smb://",Null) 'get a list of all samba groups
  
   For i = 0 To l.Size - 1
   ListView2.AddSingleLine(l.Get(i))
   Next
  
   DoEvents
  
   tmp1 = fs.Escape("c:\Program Files (x86)") 'test the escape method (available in samba as well)
   Log(tmp1)
  
End Sub

--- Jem
Is this code from your sample? Thanks. Let me try again.
 
Top