File Handling used for saving files in a recursive manner - java

I have my code generating two files with rewritable data. I need a code that continues generating the files with recursive file names and should keep all the previous files as well .
In the below code, every time i have to update my file, I have to hard code it and copy it into a new file.
I want a recursive function that saves the file, named numerically in an order(Ascending), while keeping the data in my previous file as well, everytime i run the code.
public static void main(String[] args) throws IOException
{
createFileUsingFileClass();
copyFileVersion();
fileChecker();
String data_2 = "This is the new data written in your file";
writeUsingFileWriter(data_2);
copyFileInCode(data_2);
}
private static void createFileUsingFileClass() throws IOException
{
File file = new File("C:\\Users\\esunrsa\\Documents\\file.txt");
//Create the file
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
//Write Content
FileWriter writer = new FileWriter(file);
String data_1 = " Initial data";
writer.write(data_1);
writer.close();
}
private static void copyFileVersion() {
FileInputStream ins = null;
FileOutputStream outs = null;
try {
File infile =new File("C:\\Users\\esunrsa\\Documents\\file.txt");
File outfile =new File("C:\\Users\\esunrsa\\Documents\\file_01.txt");
ins = new FileInputStream(infile);
outs = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = ins.read(buffer)) > 0) {
outs.write(buffer, 0, length);
}
ins.close();
outs.close();
System.out.println("File created successfully!!");
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
private static void fileChecker() {
File f = new File("C:\\Users\\esunrsa\\Documents\\sunrita.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File doesnt exist");
System.exit(0);
//System.out.println("File not found!");
}
}
private static void writeUsingFileWriter(String data_2) {
File file = new File("C:\\Users\\esunrsa\\Documents\\file.txt");
FileWriter fr = null;
try {
fr = new FileWriter(file);
fr.write(data_2);
} catch (IOException e) {
e.printStackTrace();
}finally{
//close resources
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void copyFileInCode(String filename) {
FileInputStream ins = null;
FileOutputStream outs = null;
try {
File infile =new File("C:\\Users\\esunrsa\\Documents\\file.txt");
File outfile =new File("C:\\Users\\esunrsa\\Documents\\file_02.txt");
ins = new FileInputStream(infile);
outs = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = ins.read(buffer)) > 0) {
outs.write(buffer, 0, length);
}
ins.close();
outs.close();
System.out.println("File created successfully!!");
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}

Related

how to zip multiples files in java , so that when we unzip , it should not be in folder

There are 3 files which I want to zip.
I am able to zip these files using the below code
public class TestZip {
public void zipFiles(List<String> files){
FileOutputStream fos = null;
ZipOutputStream zipOut = null;
FileInputStream fis = null;
try {
fos = new FileOutputStream("NeoloadProject/New folder/testing.zip");
zipOut = new ZipOutputStream(new BufferedOutputStream(fos));
for(String filePath:files){
File input = new File(filePath);
fis = new FileInputStream(input);
ZipEntry ze = new ZipEntry(input.getName());
System.out.println("Zipping the file: "+input.getName());
zipOut.putNextEntry(ze);
byte[] tmp = new byte[4*1024];
int size = 0;
while((size = fis.read(tmp)) != -1){
zipOut.write(tmp, 0, size);
}
zipOut.flush();
fis.close();
}
zipOut.close();
System.out.println("Done... Zipped the files...");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try{
if(fos != null) fos.close();
} catch(Exception ex){
}
}
}
public static void main(String a[]){
TestZip mfe = new TestZip();
List<String> files = new ArrayList<String>();
files.add("NeoloadProject/New folder/repository.xml");
files.add("NeoloadProject/New folder/scenario.xml");
files.add("NeoloadProject/New folder/settings.xml");
mfe.zipFiles(files);
}
}
So the output of the program is testing.zip
So when I unzip , all my files are in testing folder.
testing folder --> file1, file2 , file3
My requirement is that when I unzip this zip file it should directly zip , without any folder wrapped on it.

how to read a value in CSV with the value left to it

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);
}
}

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

DeflaterOutputStream won't output valid file

I'm using DeflaterOutputStream in combination with Buffered input and output streams, trying to just compress a simple file which I should be able to decompress with the second program (it also adds a number at the end of a line but this is irrelevant). However, it's not creating a valid compressed file. When I try to decompress it, it just creates a blank file. I think it might have something to do with flushing. Any thoughts?
public class Program {
static String inputFileName = "inputfile.txt";
static String outputFileName = "outputfile.txt";
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream(inputFileName);
BufferedInputStream inputBuff = new BufferedInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
BufferedOutputStream outputBuff = new BufferedOutputStream(fileOutputStream);
DeflaterOutputStream deflater = new DeflaterOutputStream(outputBuff);
int fileByte;
while ((fileByte =inputBuff.read()) != -1)
{
deflater.write(fileByte);
}
deflater.flush();
outputBuff.flush();
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Program2 {
static String inputFileName = "outputfile.txt";
static String outputFileName = "decoutputfile.txt";
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream(inputFileName);
BufferedInputStream inputBuff = new BufferedInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
BufferedOutputStream outputBuff = new BufferedOutputStream(fileOutputStream);
InflaterOutputStream inflater = new InflaterOutputStream(outputBuff);
int fileByte;
int lineCount = 1;
while ((fileByte =inputBuff.read()) != -1)
{
if (fileByte == '\n'){
inflater.write(lineCount);
lineCount++;
}
inflater.write(fileByte);
}
inflater.flush();
outputBuff.flush();
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How do I code the function of the Save button in Java?

I have an existing text file and edited some stuff in it. I want to save a line of text to that same file. Currently, my Save button will create a new file for the text file I just edited. What I want is that my Save button will just overwrite the existing file. What code do I need to write on it?
Here's my current code:
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
int choice = fc.showSaveDialog(null);
if (choice == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getAbsolutePath();
writeToFile(filename);
}
}
here's my writeToFile code:
private void writeToFile(String filename) {
Person p = getPersonFromDisplay();
PersonFileMgr.save(filename, p);
}
To overwrite a file without creating a whole new file. Use FileWriter and BufferedWriter
example:
Inside your writeToFile method
try{
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hi\n");
out.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
You could do something like this:
InputStream ios = null;
OutputStream out = null;
try {
ios = new FileInputStream(file);
byte[] buffer = new byte[SIZE];
int read;
out = new FileOutputStream(file);
while ((read = ios.read(buffer)) != -1) {
out.write(buffer, 0, read);
out.flush();
}
} catch (IOException e) {
log.error("Saving failed", e);
} finally {
if (ios != null) {
ios.close();
}
if (out != null) {
out.close();
}
}
Make the notice that in our current code you don't need several variables as choice and filename and you could inline them. There is no reason to have them.

Categories

Resources