How do I code the function of the Save button in Java? - 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.

Related

File Handling used for saving files in a recursive manner

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

Why is this not reading in?

I know I'm not doing something correctly. I know the file needs to be Serializable to read a text file.
I've got implements Serializable on the main class. But my readText and my writeText aren't converting.
Nothing is coming in when I read and when I write out the file is not text.
public static ArrayList<String> readText() {
ArrayList<String> read = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Reading serialized file",
FileDialog.LOAD);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File inFile = new File(dirPath + foName);
BufferedReader in = null;
ObjectInputStream OIS = null;
try {
in = new BufferedReader(new FileReader(inFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = null;
try {
line = in.readLine();
} catch (IOException e1) {
e1.printStackTrace();
while (line != null) {
try {
FileInputStream IS = new FileInputStream(inFile);
OIS = new ObjectInputStream(IS);
inFile = (File) OIS.readObject();
} catch (IOException io) {
io.printStackTrace();
System.out.println("An IO Exception occurred");
}
catch (ClassNotFoundException cnf) {
cnf.printStackTrace(); // great for debugging!
System.out.println("An IO Exception occurred");
} finally
{
try {
OIS.close();
} catch (Exception e) {
}
}
}
}
return read;
}
public static void writeText(ArrayList<String> file) {
ArrayList<String> write = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Saving customer file",
FileDialog.SAVE);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File outFile = new File(dirPath + foName);
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
for (int i = 0; i < write.size(); i++) {
String w = write.get(i);
out.println(file.toString());
}
}
catch (IOException io) {
System.out.println("An IO Exception occurred");
io.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
}
}
}
Nothing is coming in
You're never calling read.add(line) and you're attempting to read the file within an infinite loop inside of the catch block, which is only entered if you are not able to read the file.
Just use one try block, meaning try to open and read the file at once, otherwise, there's no reason to continue trying to read the file if it's not able to be opened
List<String> read = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(inFile)) {
String line = null;
while ((line = in.readLine()) != null) {
read.add(line); // need this
}
} catch (Exception e) {
e.printStackTrace();
}
return read;
Now, whatever you're doing with this serialized object stuff, that's completely separate, and it isn't the file or your main class that needs set to Serializable, it's whatever object you would have used a writeObject method on. However, you're reading and writing String objects, which are already Serializable.
when I write out the file is not text
Not sure what you mean by not text, but if you followed the above code, you'll get exactly what was in the initial file... Anyway, you do not need a write list variable.
You must use the individual lines of ArrayList<String> file parameter instead, but not file.toString()
for (String line:file) {
out.println(line);
}
out.close(); // always close your files and writers

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

Using Filewriter to write but the file remains empty.

I have the following code to write in three files. I have printed the Strings before writing to ensure they have some data in them, the printed Strings show the data given to them by calling this function but on creation of file the files are empty.
Please suggest something.
public static void save(String editedFileText,String srcFileText,String translFileText)throws IOException {
JFileChooser chooser = new JFileChooser();
System.out.println(editedFileText);
System.out.println(srcFileText);
System.out.println(translFileText);
int retrival = chooser.showSaveDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try {
FileWriter edit = new FileWriter(chooser.getSelectedFile()+".txt");
edit.write(editedFileText.toString());
FileWriter srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt");
srcFile.write(srcFileText.toString());
FileWriter trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt");
trans.write(translFileText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Get in the habit of creating all Writers, Readers, InputStreams and OutputStreams in try-with-resources statements. It ensures they will be properly closed:
try (FileWriter edit = new FileWriter(chooser.getSelectedFile()+".txt")) {
edit.write(editedFileText);
}
try (FileWriter srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt")) {
srcFile.write(srcFileText);
}
try (FileWriter trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt")) {
trans.write(translFileText);
}
If you're just writing a single String, you have the option of using Files.write, which allows you to forego the use of a Writer altogether:
Files.write(Paths.get(chooser.getSelectedFile()+".txt"),
editedFileText.getBytes());
Files.write(Paths.get(chooser.getSelectedFile()+"_srcText"+".txt"),
srcFileText.getBytes());
Files.write(Paths.get(chooser.getSelectedFile()+"_translFile"+".txt"),
translFileText.getBytes());
Add a finally to close the opened files, but first you need to declare them outside the try catch finally:
FileWriter edit,srcFile, trans;
edit = srcFile = trans = null;
try {
edit = new FileWriter(chooser.getSelectedFile()+".txt");
edit.write(editedFileText.toString());
srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt");
srcFile.write(srcFileText.toString());
trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt");
trans.write(translFileText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}finally{
if(edit != null)
edit.close();
if(srcFile != null)
srcFile.close();
if(trans != null)
trans.close();
}
FileWriter writer=null;
try {
writer = new FileWriter(filename);
writer.write(sb.toString());
} catch (Exception e) {
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Android Java Read and Save data doesnt work

Hey I would like to save datas and then I would like to read them and put them in a EditText
speichern.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
save();
tv.setText("gespeichert");
}
});
private void save() {
try {
File myFile = new File("bla.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(string.toString() + "\n");
myOutWriter.append(string2.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Gespeichert",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void read() {
int bla;
StringBuffer strInhalt = new StringBuffer("");
try {
FileInputStream in = openFileInput("bla.txt");
while( (bla = in.read()) != -1)
strInhalt.append((char)bla);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
What can i change?`
pelase help me
I'm usin eclipse
And i would like to safe the .txt not external.
I don't believe you are creating your file correctly:
File file = new File("test.txt");
file.createNewFile();
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write("Hello World");
fo.close();
System.out.println("file created: "+file);
url = upload.upload(file);
}
And to read this file:
try {
// open the file for reading
InputStream instream = openFileInput("test.txt");
// if file the available for reading
if (instream) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine())) {
// do something with the settings from the file
}
}
// close the file again
instream.close();
} catch (java.io.FileNotFoundException e) {
// do something if the myfilename.txt does not exits
}
And don't forget to encapsulate code with a try-catch block to catch an IOException which is thrown from these objects.
EDIT
Add this to your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
or...
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
Hope that helps! :)

Categories

Resources