Files.readAllLine() not working after FileWriting - java

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

Related

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

Java Directory Search - Text File Writer - Only 1 result appears

Hey so I'm currently having an issue with this code: [There is more code to this but this is the block that I need help with]
File fe = new File("C:\\Users\\" + System.getProperty("user.name") + "\\desktop" + "\\SearchResults.txt");
String customLoca = "C:\\Users\\" + System.getProperty("user.name") + "\\desktop";
File dir = new File(customLoca);
for (File f : dir.listFiles()){
if (f.getName().contains(".jar"))
if (f.getName().endsWith(".jar"))
try{
FileWriter fw = new FileWriter(fe);
fw.write("[!]Found: " + f.getName() + "[!]");
fw.write("\r\n");
fw.write("[!]Found: " + f.getName() + "[!]");
fw.close();
}catch(Exception ex){
}
}
}
}
I want it to print all the results however it only prints 1.
https://gyazo.com/406ab3039f3efa8f72d3dfff5732c088
Do you know a way I can make it so it prints all the results? Thanks.
The problem is that you are creating the file writer object inside loop. so it will replace the previous result hence only the last result will be present in the searchResults.txt.
To fix this problem move FileWriter fw = new FileWriter(fe); outside the for loop
Also note that you dont need both the 2 if conditions.
if if (f.getName().contains(".jar")) is true then
if (f.getName().endsWith(".jar")) also returns true, also you are missing the braces after the if statement.
File dir = new File(customLoca);
for (File f : dir.listFiles()){
if (f.getName().endsWith(".jar")) {
try{
FileWriter fw = new FileWriter(fe);
fw.write("[!]Found: " + f.getName() + "[!]");
fw.write("\r\n");
fw.write("[!]Found: " + f.getName() + "[!]");
fw.close();
}catch(Exception ex){
}
}
}

Appending to a file in android

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.

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

Buffered Writer overwriting file when not wanted

I have this code here that takes in 3 arguments, A Directory, a Filename, and a number. The program creates the filename in the directory and writes the number in it. So I can say...
>java D: myName.txt Clay 100
which will create a file named myName.txt in D: and says 100 in it.
If myName is taken up, it changes the name to myName(2), then myName(3) (if myName(2) taken up). The only problem is that when it changes the name to myName(2) and writes, it overwrites myName. I dont want it to overwrite myName, I want it to just create a new file with that name. Ive looked at similar questions and the common answer is the flush and close the writer which ive done And it still doesnt work.
Any help would be appreciated, here is my code so fart...
import java.io.*;
public class filetasktest{
public static void main(String[] args) throws IOException{
int i = 2;
String directory = args[0];
if (directory.substring(directory.length() - 1) != "/"){
directory += "/";
}
String contactName = args[1];
String contactNumber = args[2];
String finalDirectory = directory + contactName + ".contact";
File f = new File(finalDirectory);
while (f.exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
f.renameTo(new File(finalDirectory));
i++;
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(finalDirectory), "utf-8"));
writer.write(contactNumber);
} catch (IOException ex){
System.out.println(ex.getMessage());
} finally {
try {
writer.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
}
You need to use append mode
new BufferedWriter(new FileWriter(yourFileName, true));
here, true means that the txt should be appended at the end of file.
Check the FileWriter javadoc for more information.
Your problem is here:
while (f.exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
f.renameTo(new File(finalDirectory));
i++;
}
The renameTo method does not change the path of a File object; it renames a file on disk. The path of f stays the same throughout the loop: it starts out as D:/myName.txt and if a file by that name exists, the file is renamed as D:/myName(1).txt. The variable f still holds the path D:/myName.txt, which no longer names a file, and the content is written to D:/myName(1).txt, overwriting the previous content.
To fix this issue change the loop to:
while (new File(finalDirectory).exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
i++;
}
Take a look at FileInputStream(String, boolean) which will allow you to flag if the file should be appended or overwritten

Categories

Resources