Overwriting database file with another non-empty one - java

I'm trying this to overwrite the file:
File file = new File(importDir, dbFile.getName());
DataOutputStream output = new DataOutputStream(
new FileOutputStream(file, false));
output.close();
But it obviously overwrites an old file with an new empty one, and my goal is to owerwrite it with the content provided by file
How do I do that correctly?

Unfortunately, such simple operation as file copying is unobvious in Java.
In Java 7 you can use NIO util class Files as follows:
Files.copy(from, to);
Otherwise its harder and instead of tons of code, better read this carefully Standard concise way to copy a file in Java?

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.print("Enter a file name to copy : ");
str = br.readLine();
int i;
FileInputStream f1;
FileOutputStream f2;
try
{
f1 = new FileInputStream(str);
System.out.println("Input file opened.");
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
return;
}
try
{
f2 = new FileOutputStream("out.txt"); // <--- out.txt is newly created file
System.out.println("Output file created.");
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
return;
}
do
{
i = f1.read();
if(i != -1) f2.write(i);
}while(i != -1);
f1.close();
f2.close();
System.out.println("File successfully copied");

You can use
FileOutputStream fos = new FileOutpurStream(file);
fos.write(string.getBytes());
constructor which will create the new file or if exists already then overwrite it...

For my purposes it seems that the easiest way is to delete file and then copy it
if (appFile.exists()) {
appFile.delete();
appFile.createNewFile();
this.copyFile(backupFile, appFile);

Related

Error reading a txt file

I am getting this error in my code when trying to read a file saved on the external storage of my phone :
java.io.FileNotFoundException: shopping.txt: open failed: ENOENT (No such file or directory)
I can manage to write data to this file with success, what I did a lot of times.
However, I cannot access for reading this same file, giving the entire path or through another method.
The code writing and saving successfully :
File path = new File(this.getFilesDir().getPath());
String value = "vegetables";
// File output = new File(path + File.separator + fileName);
File output = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
// Toast.makeText(getBaseContext(), "File saved successfully!",
// Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,String.valueOf(output),Toast.LENGTH_LONG).show();
Log.d("MainActivity", "Chemin fichier = [" + output + "]");
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
The writing piece of code crashing my app :
try
{
File gFile;
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
//FileInputStream fis = openFileInput("/storage/emulated/0/Android/data/com.example.namour.shoppinglist/files/shopping.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null, input="";
while ((line = reader.readLine()) != null)
input += line;
Toast.makeText(MainActivity.this,line,Toast.LENGTH_LONG).show();
reader.close();
fis.close();
Toast.makeText(MainActivity.this,"Read successful",Toast.LENGTH_LONG).show();
//return input;
}
catch (IOException e)
{
Log.e("Exception", "File read failed: " + e.toString());
//toast("Error loading file: " + ex.getLocalizedMessage());
}
What am I doing wrong ?
For sure, not a problem of permissions, since I can write with success.
Many thanks for your help.
You missed to specifiy the correct path. You are looking for a file named shopping.txt in your current working directory (at runtime).
Create a new File object with the correct path and it will work:
File input = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");. You could reuse your object from writing.
While opening the file, you are simply using new File("shopping.txt").
You need to specify the parent folder, like this:
new File(getExternalFilesDir(),"shopping.txt");
I recommend you make sure of org.apache.commons.io for IO, their FileUtils and FileNameUtils libs are great. ie: FileUtils.writeStringToFile(new File(path), data); Add this to gradle if you wish to use it: implementation 'org.apache.commons:commons-collections4:4.1'
In regards to your problem. When you write your file you are using:
getApplicationContext().getExternalFilesDir(null),"shopping.txt"
But when reading your file you are using:
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
Notice that you didn't specify a path to shopping.txt simply the file name.
Why not do something like this instead:
//Get path to directory of your choice
public String GetStorageDirectoryPath()
{
String envPath = Environment.getExternalStorageDirectory().toString();
String path = FilenameUtils.concat(envPath, "WhateverDirYouWish");
return path;
}
//Concat filename with path
public String GetFilenameFullPath(String fileName){
return FilenameUtils.concat(GetStorageDirectoryPath(), fileName);
}
//Write
String fullFilePath = GetFilenameFullPath("shopping.txt");
FileUtils.writeStringToFile(new File(fullFilePath ), data);
//Read
File file = new File(fullFilePath);
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null){
text.append(line);
if(newLine)
text.append(System.getProperty("line.separator"));
}
br.close();

How to rename a txt file using Java after copying contents from another txt file

I have created a program where there is a file called groups.txt. This file contains a list of names. To delete a group, it has to exist within the file. I used the Scanner method to search through each line for the name. If it contains the line, it sets val as 1. Which triggers the val == 1 condition. What I wanted to do during this block, is try to delete groupName from the groups.txt file. To do this, I created a new txt file called TempFile which copies all the names from groups.txt EXCEPT groupName. This file is then renamed to groups.txt and the old groups.txt file is deleted.
Everything works as intended, except the renaming. The temp.txt file still exists and the groups.txt file is unchanged. I checked the boolean success, and it always returns as false. Any ideas how to solve this?
if (method.equals("delete group")){
int val = 0;
String groupName = myClient.readLine();
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
val = 1;
}
}
if (val == 1){
try {
File groupFile = new File("groups.txt");
File tempFile = new File("temp.txt");
BufferedReader reader = new BufferedReader(new FileReader(groupFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
System.out.println(groupName);
while ((currentLine = reader.readLine()) != null){
String trimLine = currentLine.trim();
if (trimLine.equals(groupName)){
continue;
} else {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
groupFile.delete();
boolean success = tempFile.renameTo("groups.txt");
} catch (IOException f){
System.err.println("File Not Found: " + f.getMessage());
} }
} catch (FileNotFoundException f){
System.err.println("File Not Found Exception: " + f.getMessage());
}
}
CODE BEFORE THE ABOVE:
if (command.equals("group")){
String method = myClient.readLine();
if (method.equals("create group")){
String groupName = myClient.readLine();
int val = 0;
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
Report.error("group name already exists, please pick another");
val = 1;
}
}
} catch (FileNotFoundException f){
System.err.println("File Not Found: " + f.getMessage());
}
if (val == 0){
try {
PrintWriter out = new PrintWriter(new FileWriter("groups.txt", true));
out.println(groupName);
out.close();
} catch (IOException e){
Report.error("IOException: " + e.getMessage());
}
}
In the second part of the code, this is where I originally update the groups.txt file. So every time the user adds a group, it updates the groups.txt file by adding the new groupName to the end of the file. First, I make sure the groupName doesn't already exist using Scanner. myClient is a BufferedReader which reads from another class which stores what the user types in the command line.
Also do not forget to close Scanner. First you should make delete() work and make sure you know your current working directory, and write your filepath relative to it. Check with:
File file = new File("abc.txt");
System.out.println(file.getAbsolutePath());
One thing might be unrelated, also check your environment because
In the Unix'esque O/S's you cannot renameTo() across file systems. This behavior is different than the Unix "mv" command. When crossing file systems mv does a copy and delete which is what you'll have to do if this is the case. The same thing would happen on Windows if you tried to renameTo a different drive, i.e. C: -> D:

Error in reading file java.io

So i'm trying to read the following string from the text file addToLibrary.txt
file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3
But when I do i get the following error:
java.io.FileNotFoundException: file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3 (No such file or directory)
Whats odd is that I got that string from a fileChooser using this method:
public static void addToLibrary(File f) {
String fileName = "addToLibrary.txt";
try {
FileWriter filewriter = new FileWriter(fileName, true);
BufferedWriter bufferedWriter = new BufferedWriter(filewriter);
bufferedWriter.newLine();
bufferedWriter.write(f.toURI().toString());
System.out.println("Your file has been written");
bufferedWriter.close();
} catch (IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
} finally {
}
}
An even stranger error is that my file reader can read things in another folder but not anything in iTunes Media.
I attempt to read all the files in the different folders with the following method:
public void getMusicDirectory() {
int index = 0;
try {
File[] contents = musicDir.listFiles();
//System.out.println(contents[3].toString());
for (int i = 0; i < contents.length; i++) {
//System.out.println("----------------------------------------"+contents.length);
String name = contents[i].getName();
//System.out.println(name);
if (name.indexOf(".mp3") == -1) {
continue;
}
FileInputStream file = new FileInputStream(contents[i]);
file.read();
System.out.println(contents[i].toURI().toString());
songsDir.add(new Song((new MediaPlayer(new Media(contents[i].toURI().toString()))), contents[i]));
file.close();
}
} catch (Exception e) {
System.out.println("Error -- " + e.toString());
}
try(BufferedReader br = new BufferedReader(new FileReader("addToLibrary.txt"))) {
//System.out.println("In check login try");
for (String line; (line = br.readLine()) != null; ) {
FileInputStream file = new FileInputStream(new File(line));
file.read();
songsDir.add(new Song(new MediaPlayer(new Media(line)), new File(line)));
file.close();
}
// line is not visible here.
} catch (Exception e) {
System.out.println("Error reading add to library-- " + e.toString());
}
}
So how can i make this work? why does the first part of the method work but not the second?
You are not having a problem reading the string
file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3
from a file. That part works fine. Your problem is after that, when you try to open the file with the path:
file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3
because that's not actually a path; it's a URI (although it can be converted to a path).
You could convert this to a path, in order to open it, but you have no reason to - your code doesn't actually read from the file (apart from the first byte, which it does nothing with) so there's no point in opening it. Delete the following lines:
FileInputStream file = new FileInputStream(contents[i]); // THIS ONE
file.read(); // THIS ONE
System.out.println(contents[i].toURI().toString());
songsDir.add(new Song((new MediaPlayer(new Media(contents[i].toURI().toString()))), contents[i]));
file.close(); // THIS ONE
and
FileInputStream file = new FileInputStream(new File(line)); // THIS ONE
file.read(); // THIS ONE
songsDir.add(new Song(new MediaPlayer(new Media(line)), new File(line)));
file.close(); // THIS ONE
file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3 is not a valid File reference, especially under Windows.
Since you've idendtified the String as a URI, you should treat it as such...
URI uri = URI.create("file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3");
Okay, but, there's no real way to read URI, but you can read a URL, so we need to convert the URI to URL, luckily, this is quite simple...
URL url = uri.toURL();
From there you can use URL#openStream to open an InputStream (which you can wrap in a InputStreamReader) and read the contents of the file, for example...
String imageFile = "file:/...";
URI uri = URI.create(imageFile);
try {
URL url = uri.toURL();
try (InputStream is = url.openStream()) {
byte[] bytes = new byte[1024 * 4];
int bytesRead = -1;
int totalBytesRead = 0;
while ((bytesRead = is.read(bytes)) != -1) {
// Somthing, something, something, bytes
totalBytesRead += bytesRead;
}
System.out.println("Read a total of " + totalBytesRead);
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
You could, however, save your self a lot of issues and stop using things like f.toURI().toString()); (File#toURI#toString) and simply use File#getPath instead...This would allow you to simply create a new File reference from the String...
Also, your resource management needs some work, basically, if you open it, you should close it. See The try-with-resources Statement for some more ideas

Android FileReader from R.raw.file

Really newbie question:
I have a .csv file that I need to read. I've put it in the raw folder. For convenience, Im' using the http://opencsv.sourceforge.net/ library for reading the file. The library provides this method for creating a CSVReader object:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
But I don0't get how to point this constructor to my file, since the file in Android is usually referenced like R.raw.file rather than a String address to the file.
Any help would be greatly appreciated.
You want to do something like this -
public void readCSVFromRawResource(Context context)
{
//this requires there to be a dictionary.csv file in the raw directory
//in this case you can swap in whatever you want
InputStream inputStream = getResources().openRawResource(R.raw.dictionary);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try
{
String word;//word
int primaryKey = 0;//primary key
Map dictionaryHash = new HashMap();
while ((word = reader.readLine()) != null)
{
if(word.length() < 7)
{
dictionaryHash.put(primaryKey,word );
primaryKey++;
if(primaryKey % 1000 == 0)
Log.v("Percent load completed ", " " + primaryKey);
}
}
//write the dictionary to a file
File file = new File(DICTIONARY_FILE_NAME);
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(DICTIONARY_FILE_NAME));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(dictionaryHash);
oos.flush();
oos.close();
Log.v("alldone","done");
}
catch (Exception ex) {
// handle exception
Log.v(ex.getMessage(), "message");
}
finally
{
try
{
inputStream.close();
}
catch (IOException e) {
// handle exception
Log.v(e.getMessage(), "message");
}
}
}
You can use this solution to get a String from the raw resource:
Android read text raw resource file
then use StringReader instead of FileReader with the CSVReader constructor.

Directory listing not refreshing

This is driving me crazy! I have a panel that displays a list of files from a directory. The list is stored in a vector. When I click on a button, a new file is created in the same directory and the list needs to be refreshed.
I don't understand why Java cannot see the new file, even though if I add a good old DIR in Dos, Dos can see the file. It's as if the new file is invisible even though I can see it and Dos can see it. I tried giving it some time (sleep, yield) but it's no use. I also tried copying to a new temp file and reading the temp but again to no avail. Here's some code (removed some irrelevant lines):
public class Button extends EncapsulatedButton {
public Button()
{
super("button pressed");
}
public void actionPerformed(ActionEvent arg0) {
//removed function here where the new file is created in the directory
//remove call to DOS that regenerates /myFileList.txt after a new file was added in the directory
//at this point, DOS can see the new file and myFileList.txt is updated, however it is read by java without the update!!!!!
//now trying to read the directory after the new file was created
Vector data = new Vector<String>();
String s = null;
// Create the readers to read the file.
try {
File f = new File("/myFileList.txt");
BufferedReader stream = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
while((s = stream.readLine()) != null)
{
data.addElement(s.trim());
}
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
util();
}
void util(){
//giving it time is not helping
Thread.yield();
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
//get the file listing through java instead of DOS - still invisible
File fLocation = new File("/myDir");
File[] filesFound = fLocation.listFiles();
for (int i = 0; i < filesFound.length; i++) {
if (filesFound[i].isFile()) {
System.out.println("**********" + filesFound[i].getName());
}
}
//last resort: copy to a temp then read from there - still not good
try{
//copy to a temp file
File inputFile = new File("/myFileList.txt");
File outputFile = new File("/myFileList_temp.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
//read the copy to see if it is updated
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("/myFileList_temp.txt");
// Get the object of DataInputStream
DataInputStream in1 = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in1));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println ("Test file read: " + strLine);
}
//Close the input stream
in1.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
I would appreciate any leads. Thank you.
myFileList.txt lokks like this:
myline1
myline2
myline3
After adding a new file in the folder,
myline4 should appear in it, then it will be read and displayed in the panel.
Honestly, your code is a mess.
You read from /myFileList.txt and do nothing with what you read, except store it in a temporary Vector. At best, this has no effect; at worst (if the file doesn't exist, for example) it throws an exception. Whatever it does, it does not create a new file.
Furthermore, I see no reference to the panel in your GUI that supposedly displays the file list. How do you expect it to get updated?
This works for me:
To refresh the directory list, call .listFiles() again.
filesFound = fLocation.listFiles();
should show the most updated directory listing. Hope this helps you.

Categories

Resources