Appending to a file in android - java

The question is how to append to an existing file. I'm using MODE_APPEND with FileOutputStream fos = openFileOutput("filename", MODE_APPEND);. The file is created and the object is saved, but when I call the method again on the same file - nothing happens. MODE_PRIVATE works but only for 1 insert as it creates a new file every time it's called. I spent the whole day researching and I couldn't find any answer so I am desperate for your help.
public void createFile (View V) throws IOException, JSONException {
JSONArray resultsLog = new JSONArray();
JSONObject exercise2;
String pickVal1 = stringArray[numPick1.getValue()];
String pickVal2 = stringArray[numPick2.getValue()];
String pickVal3 = stringArray[numPick3.getValue()];
String pickVal4 = stringArray[numPick4.getValue()];
exercise2 =new JSONObject();
exercise2.put("rep", pickVal1 + " kg " + pickVal2 + " kg " + pickVal3 + " kg " + pickVal4 + " kg ");
exercise2.put("type", caller + " on " + date);
resultsLog.put(exercise2);
String text= resultsLog.toString();
FileOutputStream fos = openFileOutput("resultsDat3", MODE_APPEND);
fos.write(text.getBytes());
fos.close();
//displayText(this,R.id.stext,resultsLog.toString());
// finish();
}

Use a FilterWriter object. It provides a constructor with the option to append writes to the current file, and even takes care of creating the file if needed.

Related

Files.readAllLine() not working after FileWriting

hoping you're doing well, this is my first question
I have a trouble:
My goal is to create java files from pieces of code (fields, attributes, constructor)
I tried to do this by altering between reading and writing file.
Reading file to get the old value , delete closing "}"
Writing in file : the new piece of code, plus closing "}"
The problem with my try is that Files.readAllLine() or FileWriter() is not working.
You can find my source code below.
public static void fillFile(String fileName, String name, String value) throws IOException {
Path path = Paths.get(fileName);
List<String> all = Files.readAllLines(path,StandardCharsets.UTF_8);
System.out.println(" the path "+Paths.get(fileName));
System.out.println(name + " :; "+ value);
System.out.println("to write " + all.toString().replaceAll(", ", " ").substring(1, (all+"").replaceAll(", ", " ").length()-1) + "\n" + name + (name.endsWith(")")?"":" = ")+ value+ (name.endsWith(")")?"":";")+"\n } ddddddddddddddddddddddd");
FileWriter test = new FileWriter(fileName,true);
test.write(all.toString().replaceAll(", ", " ").substring(1, all.toString().replaceAll(", ", " ").length()-1) + "\n" + name + (name.endsWith(")")?"":" = ")+ value+ (name.endsWith(")")?"":";")+"\n }");
//test.flush();
test.close();
}
Another question : there is an other easy way to reach my goal ?
The solution is that the FileWriter classe should have a different path that the one which File.readAllLine()use.
So we have to create a temporary file, which will be copied to the desired fileName file, then we delete the temporary file
Hope this will help people who need it. It is working !!!
public static void fillFile(String fileName, String name, String value) throws IOException {
Path path = Paths.get(fileName);
List<String> all = null;
if (path.toFile().exists()) {
all = Files.readAllLines(path,StandardCharsets.UTF_8);}
if(all!= null) System.out.println(path + " the size of "+ all.toArray(new String[all.size()])+"");
Path path2 = Files.createTempFile(path.getParent(),"test-file", ".java");
Files.write(path2, ((all+"").replaceAll(", ", "\n").replaceAll("\\[", "").replaceAll("\\]", "").substring(1, ((all+"").replaceAll(", ", " ").replaceAll("\\[", "").replaceAll("\\]", "")).length()-1) + "\n" + name + value+ "\n" +"}").getBytes());
Files.copy(path2, path, StandardCopyOption.REPLACE_EXISTING);
Files.deleteIfExists(path2);
}

getId3v1Tag() returns null

This is the method:
public void createMp3Array() throws InvalidDataException, IOException, UnsupportedTagException {
MusicFile song;
String trackName;
String artistName;
String albumInfo = "";
String genre = "";
byte[] musicFileExtract;
Mp3File mp3file;
for (final File f : music.listFiles()) {
ID3v1 tag;
mp3file = new Mp3File(f.getAbsolutePath());
tag = mp3file.getId3v1Tag();
System.out.println(f.getAbsolutePath() + " " + tag);
trackName = tag.getTitle();
artistName = tag.getArtist();
/*albumInfo = tag.getAlbum();
System.out.println("info " + albumInfo);
genre = tag.getGenre() + " (" + id3v1Tag.getGenreDescription() + ")";
System.out.println("genre " + genre);*/
song = new MusicFile(trackName,artistName,albumInfo,genre);
songs.add(song);
System.out.println("wtf");
}
}
The line trackName = tag.getTitle(); returns gives me a NullPointerException every time except one. Everything works properly for the first mp3 file I tried, and it cannot work for any other.
Edit: I posted it accidentally without finishing editing my question sorry. The context is that I have to read a folder of mp3s and store their details in an array of MusicFile instances. There are two threads reading two seperate folders-I dont know if that has anything to do with it-. This is the error: Exception in thread "Thread-0" java.lang.NullPointerException

Logic issue to update text file - Java

I'm having a logic issue to update a text file via user input.
I have a text file containing product information (ID;Name;Cost;Stock) :
001;Hand Soap;2.00;500
In order to add a product the user calls a function addProduct in order to either update a product if the product name already exists in the file or append to the text file if it does not yet exist. I'm unsure of two things : how to append only once (for the moment it's appending for every line it reads..) and how to deal with an empty text file.
This is how addProduct looks:
public void addProduct(Product product, int amountReceived) throws FileNotFoundException, IOException {
newProduct = product;
String productParams = newProduct.getProduct();
String productID = newProduct.getProductID();
int productStock = newProduct.getProductStock();
String productName = newProduct.getProductName();
String tempFileName = "tempFile.txt";
System.out.println("Attempting to Add Product : " + newProduct.getProduct());
BufferedReader br = null;
BufferedWriter bw = null;
try {
FileInputStream fstream = new FileInputStream(ProductMap.productFile);
br = new BufferedReader(new InputStreamReader(fstream));
String line;
StringBuilder fileContent = new StringBuilder();
while ((line = br.readLine()) != null) {
System.out.println("Line : " + line);
String [] productInfo = line.split(";");
System.out.println("Added Product Info length : " + productInfo.length);
if (productInfo.length > 0) {
if (productInfo[1].equals(productName))
{
System.out.println("Adding existing product");
System.out.println("Product Info : " + String.valueOf(productInfo[3]));
//line = line.replace(String.valueOf(productInfo), String.valueOf(productStock - amountSold));
productInfo[3] = String.valueOf(Integer.parseInt(productInfo[3]) + amountReceived);
String newLine = productInfo[0] + ";" + productInfo[1] + ";" + productInfo[2] + ";" + productInfo[3];
fileContent.append(newLine);
fileContent.append("\n");
System.out.println("Updated Product Info : " + String.valueOf(Integer.parseInt(productInfo[3]) + amountReceived));
System.out.println("Line :" + newLine);
} else {
fileContent.append(line);
fileContent.append("\n");
fileContent.append(productParams);
fileContent.append("\n");
//fileContent.append(productParams + "\n");
//System.out.println("Product Name : " + productInfo[1]);
//System.out.println("The full product info : " +productParams);
}
}
br.readLine();
}
if (br.readLine() == null) {
fileContent.append(productParams);
}
System.out.println("Product Updated File Contents : " + fileContent);
FileWriter fstreamWrite = new FileWriter(ProductMap.productFile);
BufferedWriter out = new BufferedWriter(fstreamWrite);
System.out.println("File Content : " + fileContent);
out.write(fileContent.toString());
out.close();
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
At a high level, a simple text file may not be the best choice for this use. This implementation requires enough memory to hold the entire file.
If you only had additions and could just append to the file directly, things would be easier. A database would seem to be the best choice. Somewhere between a database and a simple text file, a RandomAccessFile could help if the data could be written with standard lengths for each field. Then you could overwrite a particular row rather than having to rewrite the whole file.
Given the constraints of the current setup, I can't think of a way around writing all the data each time the file is updated.
To get around the empty file problem, you could skip the else condition of the current loop So the new data would not be added to the fileContent StringBuffer. Then when writing the data back out, you could either write the new data before or after the other information from the file.
Also, the readLine at the bottom of the loop is not needed. Any row that is read at the bottom of the loop will be skipped over and not really processed when the read at the top of the loop gets the next line.

PrintWriter not writing to text file

I'm trying to create a save feature which outputs stored data to a text file. I've tried using a Printwriter to write to the file and although I'm not getting any errors and the output seems to be correct, the text file remains blank. Here is my code:
public void saveConfiguration() throws IOException{
PrintWriter pw = new PrintWriter("locos.txt");
for (int i = 0; i < currentTrains.size(); i++) {
//confirm data is correct
System.out.println(currentTrains.get(i).getAddress() + " " +
currentTrains.get(i).getName() + " " + "\n");
//write to file
pw.write(currentTrains.get(i).getAddress() + " " +
currentTrains.get(i).getName() + " " + "\n");
}
pw.close();
//for testing
System.out.println("File Saved");
}
Here's what's on the console:
8 class 08
55 Jinty
44 BR44
File Saved
The above data that gets printed out is correct, but it's not getting written to the file. Can anyone explain how to do this properly?
Edit: I don't know if this is relevant, but I'm running this on a Tomcat server.
You should try handling the PrintWriter and a Filerwriter instead...
Example:
PrintWriter pw = new PrintWriter(new FileWriter("locos.txt"));

Java — Log file only saving the latest item

I am writing an app in Java (new developer) and I am trying to save messages and things like that within a log file (logs/[date].txt). The problem I am getting is that it's overwriting each time, rather than appending the values to my file.
Here is my code:
public void onMessage(String channel, String nick, String account, String hostname, String message) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss dd/MM/yyyy");
SimpleDateFormat sdfd = new SimpleDateFormat("dd/MM/yyyy");
Date now = new Date();
try {
/* Check if the logs folder exists */
File logdir = new File("logs/");
boolean result = true;
if (!logdir.exists()) {
try {
logdir.mkdir();
}catch(Exception e){
System.err.println("[ERROR] Could not make directory 'logs/'");
result = false;
}
}
/* Check if the log file exists */
File fcheck = new File("logs/" + sdfd.format(now).replace("/", "-") + ".txt");
if (!fcheck.exists()) {
try {
fcheck.createNewFile();
}catch (Exception e){
System.err.println("[ERROR] Could not make log file 'logs/" + sdfd.format(now).replace("/", "-") + ".txt'");
}
}
/* Write to file */
if (result) {
FileWriter file = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt");
PrintWriter write = new PrintWriter(file);
String entry = "[" + sdf.format(now) + "] [" + channel + "] " + nick + " (" + account + ") > " + message + "\n";
write.append(entry);
write.close();
file.close();
}else{
System.err.println("[ERROR] Could not save line to log file.");
}
}catch (Exception e){
System.err.println("[ERROR] Could not save line to log file.");
}
}
Sorry if this isn't amazingly clear, but I'm still learning Java.
As you can see, I have write.append(entry); — which I thought would append \n to my log file, thus allowing me to save and save and keep all the entries.
You are closing the PrintWriter on every entry - a new instance is created everytime you call that method and the file is overwritten.
If you do not want to change this, you can set the FileWriter to append mode by using FileWriter(String, boolean).
FileWriter file = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt", true);
PrintWriter write = new PrintWriter(file);
When creating object of type File , add second parameter true , and the file will be appended
FileWriter fcheck = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt",true);
Set the append parameter of FileWriter to true:
FileWriter file = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt", true);

Categories

Resources