Parse a Path from Java program - java

Have a file on specified path /foo/file-a.txt and that file contains a path of another file
file-a.txt contains: /bar/file-b.txt this path at line one. need to parse the path of file-b.txt and zip that file and move that zipped file to another path /too/ from my Java code.
I been till the below code then i m stuck.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Reader
{
public static void main(String[] args)
{
BufferedReader br = null;
try
{
String CurrentLine;
br = new BufferedReader(new FileReader("/foo/file-a.txt"));
while ((CurrentLine = br.readLine()) != null)
{
System.out.println(CurrentLine);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
am getting path as text, help would be appreciated. Thanks in advance

For the actual zipping of the file, this page may be of help.
As a general note, this code will replace the current existing zip file.
public class TestZip02 {
public static void main(String[] args) {
try {
zip(new File("TextFiles.zip"), new File("sample.txt"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void zip(File zip, File file) throws IOException {
ZipOutputStream zos = null;
try {
String name = file.getName();
zos = new ZipOutputStream(new FileOutputStream(zip));
ZipEntry entry = new ZipEntry(name);
zos.putNextEntry(entry);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = fis.read(byteBuffer)) != -1) {
zos.write(byteBuffer, 0, bytesRead);
}
zos.flush();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
zos.closeEntry();
zos.flush();
} finally {
try {
zos.close();
} catch (Exception e) {
}
}
}
}
For moving the file, you can use File.renameTo, here's an example.
Hope this helps!

Related

Write JSON Object to file- append not working

I'try to save my custom JSONObject into the file.Everything working correct but I can't append json into file.For example,If I click twice to save json,in my file I have one element.Here is a my source
public class TransactionFileManager {
public static final File path = Environment.
getExternalStoragePublicDirectory(Environment.getExternalStorageState() + "/myfolder/");
public static final File file = new File(path, "transaction1.json");
public static String read() {
String ret = null;
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try {
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
bufferedReader.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return ret;
}
public static void writeToFile(JSONObject data) {
if (!path.exists()) {
path.mkdirs();
}
try {
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fOut);
outputStreamWriter.append(data.toString());
outputStreamWriter.close();
fOut.flush();
fOut.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
}
How I can append json object into my .json file.What's a wrong in my code
thanks

How to copy files in Android in one go? Not create a tens lines of code! Smth like in a sample

I need to copy file from one place to another. I have found good solution :
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileCopyTest {
public static void main(String[] args) {
Path source = Paths.get("/Users/apple/Desktop/test.rtf");
Path destination = Paths.get("/Users/apple/Desktop/copied.rtf");
try {
Files.copy(source, destination);
} catch (IOException e) {
e.printStackTrace();
}
}
}
This library work good, but in doesn't available in Android...
I try figure out which way i should use instead of, but it any suggestion... I am almost sure that it should be a library which allow copy files in one go.
If someone know say please, i am sure it will be very helpful answer for loads of people.
Thanks!
Well with commons-io, you can do this
FileInputStream source = null;
FileOutputStream destination = null;
try {
source = new FileInputStream(new File(/*...*/));
destination = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), /*...*/);
IOUtils.copy(source, destination);
} finally {
IOUtils.closeQuietly(source);
IOUtils.closeQuietly(destination);
}
Just add
compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
to the build.gradle file
try this code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class CopyFile {
public static void main(String[] args) {
File sourceFile = new File(
"/Users/Neel/Documents/Workspace/file1.txt");
File destFile = new File(
"/Users/Neel/Documents/Workspace/file2.txt");
/* verify whether file exist in source location */
if (!sourceFile.exists()) {
System.out.println("Source File Not Found!");
}
/* if file not exist then create one */
if (!destFile.exists()) {
try {
destFile.createNewFile();
System.out.println("Destination file doesn't exist. Creating
one!");
} catch (IOException e) {
e.printStackTrace();
}
}
FileChannel source = null;
FileChannel destination = null;
try {
/**
* getChannel() returns unique FileChannel object associated a file
* output stream.
*/
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (source != null) {
try {
source.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (destination != null) {
try {
destination.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Use this utility class to read/write file in sdcard:
public class MyFile {
String TAG = "MyFile";
Context context;
public MyFile(Context context){
this.context = context;
}
public Boolean writeToSD(String text){
Boolean write_successful = false;
File root=null;
try {
// check for SDcard
root = Environment.getExternalStorageDirectory();
Log.i(TAG,"path.." +root.getAbsolutePath());
//check sdcard permission
if (root.canWrite()){
File fileDir = new File(root.getAbsolutePath());
fileDir.mkdirs();
File file= new File(fileDir, "samplefile.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write(text);
out.close();
write_successful = true;
}
} catch (IOException e) {
Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());
write_successful = false;
}
return write_successful;
}
public String readFromSD(){
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"samplefile.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
return text.toString();
}
#SuppressLint("WorldReadableFiles")
#SuppressWarnings("static-access")
public Boolean writeToSandBox(String text){
Boolean write_successful = false;
try{
FileOutputStream fOut = context.openFileOutput("samplefile.txt",
context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(text);
osw.flush();
osw.close();
}catch(Exception e){
write_successful = false;
}
return write_successful;
}
public String readFromSandBox(){
String str ="";
String new_str = "";
try{
FileInputStream fIn = context.openFileInput("samplefile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br=new BufferedReader(isr);
while((str=br.readLine())!=null)
{
new_str +=str;
System.out.println(new_str);
}
}catch(Exception e)
{
}
return new_str;
}
}
Note you should give this permission in the AndroidManifest file.
Here permision
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
For more details visit : http://www.coderzheaven.com/2012/09/06/read-write-files-sdcard-application-sandbox-android-complete-example/
Android developer official Docs

How can I run executable in assets?

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

Fileinput stream / loading a simple txt file

Does anyone know why this crashes? All I'm doing is reading in a file in a txt file from my raw folder and when I click the load button in the other activity window, the code breaks when I call the variable testing within the file reader object upon click. log.d(null, ReadFileObject.fileText) Thanks in advance!
public class ReadFile extends Activity{
public String test;
public String testing;
protected void onCreate(Bundle savedInstanceState) {
}
public void fileText() {
InputStream fis;
fis = getResources().openRawResource(R.raw.checkit);
byte[] input;
try {
input = new byte [fis.available()];
while(fis.read() != -1)
{
test += new String (input);
}
testing = test;
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}
/* InputStream fis = null;
try {
fis = getResources().openRawResource(R.raw.checkit);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String nextLine;
int i = 0, j = 0;
while ((nextLine = br.readLine()) != null) {
if (j == 5) {
j = 0;
i++;
}
test += nextLine;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
} finally {
if (fis != null) {
try { fis.close(); }
catch (IOException ignored) {}
}
}*/
}
}
Your code is broken here:
byte[] input;
input = new byte [fis.available()];
while(fis.read() != -1) {
test += new String (input);
}
testing = test;
fis.close();
In Java available() is unreliable (read the Javadoc).... and may even return 0. You should instead use a loop similar to:
InputStream fis = getResources().openRawResource(R.raw.checkit);
try {
byte[] buffer = new byte[4096]; // 4K buffer
int len = 0;
while((len = fis.read(buffer)) != -1) {
test += new String (buffer, 0, len);
}
testing = test;
} catch (IOException ioe) {
ioe.printStackTrace();
// make sure you do any other appropriate handling.
} finally {
fis.close();
}
(although using string concatenation is probably not the best idea, use a StringBuilder).
Your class extends `activity but theres nothing inside oncreate. If you need a simple java program try to create New java Project . Since you extend activity you should setcontentview(yourLayout). Then call your method from oncreate and do your stuffs

why it is always showing file is not found

public static void main(String[] args) throws IOException {
String filename = "C:\\audiofile.wav";
InputStream in = null;
try{
in = new FileInputStream(filename);
}
catch(FileNotFoundException ex){
System.out.println("File not found");
}
AudioStream s = null;
s = new AudioStream(in);
AudioPlayer.player.start(s);
}
i have written this code in netbeans. Name of my audio file is audiofile.wav. But it is all time showing the exception "file not found". Can anyone help me ???
root folders in C drive of Windows Vista and above are protected by UAC. This requires you to run the java executable in Administrative mode.
However, you can shift the wav file elsewhere, where UAC will not interfere(like Documents folder of your currently logged in user) or the root of a different drive(Eg. D:\ and E:)
Also, make sure that the audiofile.wav is indeed in the said location(C:\audiofile.wav)
I think first, you should paste your exception code!
then, I think java I/O support the both two way:
"C:/audiofile.wav"
"C:\audiofile.wav"
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
// write your code here
String fileLocation = "C:\\1.diff";
String fileLocation1 = "C:/1.diff";
try {
FileInputStream f = new FileInputStream(fileLocation);
BufferedReader reader = new BufferedReader(new InputStreamReader(f));
String line = reader.readLine();
System.out.println("11111111111111111111111111");
while (line != null) {
// Process line
line = reader.readLine();
System.out.println(line);
}
System.out.println("11111111111111111111111111");
} catch (Exception ex) {
System.out.println(ex);
}
try {
FileInputStream ff = new FileInputStream(fileLocation1);
BufferedReader reader1 = new BufferedReader(new InputStreamReader(ff));
String line1 = reader1.readLine();
System.out.println("2222222222222222222222222");
while (line1 != null) {
// Process line
line1 = reader1.readLine();
System.out.println(line1);
}
System.out.println("2222222222222222222222222");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
it works. I don't know what you did, anyway paste your error msg!
====
```
private static void B() {
String filename = "C:\\test.wav";
InputStream in = null;
try {
in = new FileInputStream(filename);
} catch (FileNotFoundException ex) {
System.out.println("File not found");
}
try {
AudioStream s = new AudioStream(in);
AudioPlayer.player.start(s);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
```
it works!
Try just placing your file in a different location and see what happens
ProjectRootDir
audiofile.wav
src
And running this String
String filename = "audiofile.wav";

Categories

Resources