i want to know how to read and write text to a .txt file in j2me help me thanks...
public String readFile(String path)
{
InputStream is = null;
FileConnection fc = null;
String str = "";
try
{
fc = (FileConnection)Connector.open(path, Connector.READ_WRITE);
if(fc.exists())
{
int size = (int)fc.fileSize();
is= fc.openInputStream();
byte bytes[] = new byte[size];
is.read(bytes, 0, size);
str = new String(bytes, 0, size);
}
}
catch (IOException ioe)
{
Alert error = new Alert("Error", ioe.getMessage(), null, AlertType.INFO);
error.setTimeout(1212313123);
Display.getDisplay(main).setCurrent(error);}
finally
{
try
{
if (null != is)
is.close();
if (null != fc)
fc.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
return str;
}
void writeTextFile(String fName, String text)
{
OutputStream os = null;
FileConnection fconn = null;
try
{
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
fconn.setHidden(false);
// fconn.setReadable(true);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
if (null != os)
os.close();
if (null != fconn)
fconn.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}
Related
I am trying to unzip files in the FTP location, but when i unzip i am not able to get all the files in FTP server, but when i try the code to unzip files to local machine it is working. I am sure somewhere while writing the data to FTP i am missing something.Below is my code. Please help me on this.
public void unzipFile(String inputFilePath, String outputFilePath) throws SocketException, IOException {
FileInputStream fis = null;
ZipInputStream zipIs = null;
ZipEntry zEntry = null;
InputStream in = null;
FTPClient ftpClientinput = new FTPClient();
FTPClient ftpClientoutput = new FTPClient();
String ftpUrl = "ftp://%s:%s#%s/%s;type=i";
ftpClientinput.connect(server, port);
ftpClientinput.login(user, pass);
ftpClientinput.enterLocalPassiveMode();
ftpClientinput.setFileType(FTP.BINARY_FILE_TYPE);
String uploadPath = "path";
ftpClientoutput.connect(server, port);
ftpClientoutput.login(user, pass);
ftpClientoutput.enterLocalPassiveMode();
ftpClientoutput.setFileType(FTP.BINARY_FILE_TYPE);
try {
// fis = new FileInputStream(inputFilePath);
String inputFile = "/Srikanth/RecordatiFRA_expenses.zip";
String outputFile = "/Srikanth/FR/";
in = ftpClientinput.retrieveFileStream(inputFile);
zipIs = new ZipInputStream(new BufferedInputStream(in));
while ((zEntry = zipIs.getNextEntry()) != null) {
try {
byte[] buffer = new byte[4 * 8192];
FileOutputStream fos = null;
OutputStream out = null;
// String opFilePath = outputFilePath + zEntry.getName();
String FTPFilePath = outputFile + zEntry.getName();
// System.out.println("Extracting file to "+opFilePath);
System.out.println("Extracting file to " + FTPFilePath);
// fos = new FileOutputStream(opFilePath);
out = ftpClientoutput.storeFileStream(FTPFilePath);
// System.out.println(out);
int size;
while ((size = zipIs.read(buffer, 0, buffer.length)) != -1) {
// fos.write(buffer, 0 , size);
out.write(buffer, 0, size);
}
// fos.flush();
// fos.close();
} catch (Exception ex) {
ex.getMessage();
}
}
zipIs.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (ftpClientinput.isConnected()) {
ftpClientinput.logout();
ftpClientinput.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I am using a FileOutputStream to create a file in an activity that is not my MainActivity. The file is created, and when I destroy the activity, the data I want is written, but when I relaunch the activity from my MainActivity, the file cannot be found. What can I change in my code so that I don't get a fileNotFoundException? The relevant code is here:
try {
fis = new FileInputStream("words");
ois = new ObjectInputStream(fis);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
EOFException eof = null;
int counter = 0;
if (fnfexception == null) {
while (eof == null) {
try {
if (words == null) words = new Dict[1];
else words = Arrays.copyOf(words, counter + 1);
words[counter] = (Dict) ois.readObject();
counter++;
} catch (EOFException end) {
eof = end;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
wordStartCount = counter;
wordCount = counter;
fnfexception = null;
try {
fos = openFileOutput("words", Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
You used wrong way to read from an internal file, use the following code
try {
FileInputStream fis = context.openFileInput("file_name");
int content;
StringBuilder str = new StringBuilder();
while ((content = fis.read()) != -1)
str.append((char) content);
fis.close();
String savedText = str.toString();
} catch (IOException e) {
e.printStackTrace();
}
How can I add a executable into assets and run it in Android and show the output?
I've a executable that will work. I assume there will need to be some chmod in the code.
Thank you.
here is my answer
put copyAssets() to your mainactivity.
someone's 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(getFilesDir(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
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);
}
}
also here is code to run command
public String runcmd(String cmd){
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer out = new StringBuffer();
while ((read = in.read(buffer)) > 0) {
out.append(buffer, 0, read);
}
in.close();
p.waitFor();
return out.substring(0);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
you may need to change it to
String prog= "programname";
String[] env= { "parameter 1","p2"};
File dir= new File(getFilesDir().getAbsolutePath());
Process p = Runtime.getRuntime().exec(prog,env,dir);
to ensure proper parameter handling
also add this to your main code
to check proper copying of files
String s;
File file4 = new File(getFilesDir().getAbsolutePath()+"/executable");
file4.setExecutable(true);
s+=file4.getName();
s+=file4.exists();
s+=file4.canExecute();
s+=file4.length();
//output s however you want it
should write: filename, true, true, correct filelength.
Place your executable in raw folder, then run it by using ProcessBuilder or Runtime.exec like they do here http://gimite.net/en/index.php?Run%20native%20executable%20in%20Android%20App
I got this code for downloading my files:
public static void download()
throws MalformedURLException, IOException
{
BufferedInputStream in = null;
FileOutputStream out = null;
try
{
in = new BufferedInputStream(new URL("https://www.dropbox.com/s/1uff8eeujplz4sf/files.zip?dl=1").openStream());
out = new FileOutputStream(System.getProperty("user.home") + "/Adasti/files.zip");
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
out.write(data, 0, count);
}
} catch (MalformedURLException e1)
{
e1.printStackTrace();
} catch (IOException e2)
{
e2.printStackTrace();
} finally
{
if (in != null)
in.close();
if (out != null)
out.close();
}
}
I want to print out the percentage of the download while its downloading. Is this possible with my method and if yes, how will I do it?
You have to get the file size before start the download. Be carefull, not always the server can give you the file size (for sample streaming or some file server). Try this:
/**
*
* #param remotePath
* #param localPath
*/
public static void download(String remotePath, String localPath) {
BufferedInputStream in = null;
FileOutputStream out = null;
try {
URL url = new URL(remotePath);
URLConnection conn = url.openConnection();
int size = conn.getContentLength();
if (size < 0) {
System.out.println("Could not get the file size");
} else {
System.out.println("File size: " + size);
}
in = new BufferedInputStream(url.openStream());
out = new FileOutputStream(localPath);
byte data[] = new byte[1024];
int count;
double sumCount = 0.0;
while ((count = in.read(data, 0, 1024)) != -1) {
out.write(data, 0, count);
sumCount += count;
if (size > 0) {
System.out.println("Percentace: " + (sumCount / size * 100.0) + "%");
}
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
} finally {
if (in != null)
try {
in.close();
} catch (IOException e3) {
e3.printStackTrace();
}
if (out != null)
try {
out.close();
} catch (IOException e4) {
e4.printStackTrace();
}
}
}
The call to this method is something like this:
download("https://www.dropbox.com/s/1uff8eeujplz4sf/files.zip?dl=1", System.getProperty("user.home") + "/files.zip");
I'm using the code below to try and move my database file to my sdcard. I have no problems except that I get a redline under sd. Any ideas?
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "\\data\\application.package\\databases\\name";
String backupDBPath = "name";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src;
try {
src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
try {
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
You can only use a variable if you create an instance of it:
Put this before your code:
File sd = Environment.getExternalStorageDirectory();
if you are using SQLite database try this:
public class _DBHelper extends SQLiteOpenHelper {
public boolean backUp() throws Exception
{
InputStream input = null;
OutputStream output = null;
try {
SQLiteDatabase db = this.getReadableDatabase();
String strSource = db.getPath();
String strDest = Utilities.getAppDocumentsFolder(_context) + "/"
+ DATABASE_NAME;
File fileDest = new File(strDest);
if (fileDest.exists())
{
fileDest.delete();
}
input = new FileInputStream(strSource);
output = new FileOutputStream(strDest);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} catch (Exception e) {
throw e;
} finally
{
if (output != null)
{
output.flush();
output.close();
}
if (input != null)
{
input.close();
}
}
return true;
}
}