Write from file to ArrayList - java

For the program to work, it is necessary to write data from the file to the arraylist, but how to make the written element not equal to null in the loop? That is, so that the loop stops its execution as soon as it reads all the lines from the file
public static void readFromFile(String path, String filename) throws IOException {
ArrayList<String> ip = new ArrayList<>();
try {
File file = new File(path + "\\" + filename);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
ip.add(br.readLine());
while ((ip.add(br.readLine()) != null)) {
//writing to a variable
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

ip.add(...) returns a boolean. This code won't compile, because a boolean is a primitive, and thus can never be null.
Move the add inside the loop:
String line;
while ((line = br.readLine()) != null) {
ip.add(line);
}

Here is the better way to read all lines:
Files.readAllLines(Paths.get("path_to_file"), StandardCharsets.UTF_8)

Related

BufferedReader.readLine() returning all lines as null

I have some very simple code to ready content of txt file, line by line and put it into String[], however buffered reader return all lines as "null" - any idea on what might be the reason? *I want to use buffered reader and not other options as this is just part of java training excersise and mostly I want to understand where is the mistake i made. thanks!
public static void readFile (String path){
File file = new File(path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
int lineCount = (int) br.lines().count();
String[] passwords = new String[lineCount];
for (int i=0; i<lineCount; i++){
passwords[i] = br.readLine();;
System.out.println(passwords[i]);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
By using the lines() method you basically move the buffered reader position to the end of the file. It's like you already read these lines.
Try using this in order to iterate through all lines:
while ((line = br.readLine()) != null) {
// Use the line variable here
}
Use br.lines() or br.readLine() to consume the input, but not both at the same time. This version does the same using just the stream to String[], and closes the inputs in try with resources block:
public static String[] readFile(Path path) throws IOException {
try (BufferedReader br = Files.newBufferedReader(path);
Stream<String> stream = br.lines()) {
return stream.peek(System.out::println)
.collect(Collectors.toList())
.toArray(String[]::new);
}
}
String[] values = readFile(Path.of("somefile.txt"));

BufferedReader returns file that does not match the original

I am using a BufferedReader to read a file and store each line in a String ArrayList. However, after running the BufferedReader, reading the file, storing it, and printing the ArrayList, I get something different from the original file.
My code to read file:
public File shooterUIFile = new File("./src/com/xyfurion/hudedit/bin/resources/ShooterUI.ini");
public ArrayList<String> shooterUIRead = new ArrayList<>();
public ArrayList<String> shooterUIWrote = new ArrayList<>();
public void readHUDFile(){
try {
FileReader fileReader = new FileReader(shooterUIFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while (bufferedReader.readLine() != null)
shooterUIRead.add(bufferedReader.readLine());
for (int i = 0; i < shooterUIRead.size(); i++)
System.out.println(shooterUIRead.get(i));
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + shooterUIFile + "'");
ex.printStackTrace();
}
catch(IOException ex) {
System.out.println("Error reading file '" + shooterUIFile + "'");
ex.printStackTrace();
}
}
Output (File printed): PASTEBIN
Original File: PASTEBIN
You are only keeping every other line , since you are calling readLine twice each iteration and discarding the first read line (the one in the while condition).
You may avoid it this way :
String line = null;
while ((line = bufferedReader.readLine()) != null)
shooterUIRead.add(line);

Writing to File duplicating data the second time JAVA

I'm creating a program to remove doctors from an arrayList that is utilising a queue. This works the first time perfectly however, the second time it's duplicating the data inside the text file. How can I solve this?
/**
*
* #throws Exception
*/
public void writeArrayListToFile() throws Exception {
String path = "src/assignment1com327ccab/DoctorRecordsFile.txt";
OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(path));
BufferedWriter br = new BufferedWriter(os);
PrintWriter out = new PrintWriter(br);
DoctorNode temp; //create a temporary doctorNode object
temp = end; //temp is equal to the end of the queue
//try this while temp is not equal to null (queue is not empty)
StringBuilder doctor = new StringBuilder();
while (temp != null) {
{
doctor.append(temp.toStringFile());
doctor.append("\n");
//temp is equal to temp.getNext doctor to get the next doctor to count
temp = temp.getNext();
}
}
System.out.println("Finished list");
System.out.println("Doctors is : " + doctor.toString());
out.println(doctor.toString());
System.out.println("Done");
br.newLine();
br.close();
}
This is not 100% solution but I think it will give you the right directions. I don't want to do 100% work for you :)
In my comment I said
Read file content
Store it in variable
Remove file
Remove doctors from variable
Write variables to new file
So, to read file content we would use something file this (if it's txt file):
public static String read(File file) throws FileNotFoundException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file.getAbsoluteFile()));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
if (line != null) sb.append(System.lineSeparator());
}
String everything = sb.toString();
return everything;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
This method returns String as file content. We can store it in a variable like this:
String fileContent = MyClass.read(new File("path to file"));
Next step would be to remove our file. Since we have it in memory, and we don't want duplicate values...
file.delete();
Now we should remove our doctors from fileContent. It's basic String operations. I would recommend using method replace() or replaceAll().
And after the String manipulation, just write fileContent to our file again.
File file = new File("the same path");
file.createNewFile();
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true), "UTF-8"));
out.write(fileContent);
out.flush();
out.close();

Iterative function issue

Im having some issues with a function that I have written. The function basically takes a file and a string into the method as parameters and searches the file for that string and replaces it with "".
public void removeReminder(File a, String search) throws IOException {
File tempFile = File.createTempFile("file", ".txt", a.getParentFile());
BufferedReader br = new BufferedReader(new FileReader(a));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
for (String line; (line = br.readLine()) != null;) {
line = line.replace(search, "");
pw.println(line);
}
br.close();
pw.close();
a.delete();
tempFile.renameTo(a);
}
I then have 3 text files that I need to run this method for. Below is the code where i run the function.
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// TODO
try {
String names = reminderNameField.getText();
String date = reminderDate.getText();
String details = reminderDetailsField.getText();
File fileName = new File("reminderNames.txt");
File fileDate = new File("reminderDate.txt");
File fileDetails = new File("reminderDetails.txt");
removeReminder(fileName, names);
removeReminder(fileDate, date);
removeReminder(fileDetails, details);
} catch (IOException e){
e.printStackTrace();
}
I dont know why this isnt working. It works for the first iteration (e.g removeReminder(fileName, names);) But it doesnt work for the other ones, it seems to just ignore them :s can anyone tell me why this is?
I always flush printwriter. Try flushing PrintWriter before calling close().
pw.flush();

Reading multiple text file in Java

I have few text files. Each text file contains some path and/or the reference of some other file.
File1
#file#>D:/FilePath/File2.txt
Mod1>/home/admin1/mod1
Mod2>/home/admin1/mod2
File2
Mod3>/home/admin1/mod3
Mod4>/home/admin1/mod4
All I want is, copy all the paths Mod1, Mod2, Mod3, Mod4 in another text file by supplying only File1.txt as input to my java program.
What I have done till now?
public void readTextFile(String fileName){
try {
br = new BufferedReader(new FileReader(new File(fileName)));
String line = br.readLine();
while(line!=null){
if(line.startsWith("#file#>")){
String string[] = line.split(">");
readTextFile(string[1]);
}
else if(line.contains(">")){
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
line=br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Currently my code reads the contents of File2.txt only, control does not come back to File1.txt.
Please ask if more inputs are required.
First of all you are jumping to another file without closing the current reader and when you come back you lose the cursor. Read one file first and then write all its contents that match to another file. Close the current reader (Don't close the writer) and then open the next file to read and so on.
Seems pretty simple. You need to write your file once your svnLinks Map is populated, assuming your present code works (haven't seen anything too weird in it).
So, once the Map is populated, you could use something along the lines of:
File newFile = new File("myPath/myNewFile.txt");
// TODO check file can be written
// TODO check file exists or create
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream(newFile);
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
for (String key: svnLinks.keySet()) {
bw.write(key.concat(" my separator ").concat(svnLinks.get(key)).concat("myNewLine"));
}
}
catch (Throwable t) {
// TODO handle more gracefully
t.printStackTrace();
if (bw != null) {
try {
bw.close();
}
catch (Throwable t) {
t.printStackTrace();
}
}
Here is an non-recursive implementation of your method :
public static void readTextFile(String fileName) throws IOException {
LinkedList<String> list = new LinkedList<String>();
list.add(fileName);
while (!list.isEmpty()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(list.pop())));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("#file#>")) {
String string[] = line.split(">");
list.add(string[1]);
} else if (line.contains(">")) {
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
}
}
Just used a LinkedList to maintain the order. I suggest you to add some counter if you to limit the reading of files to a certain number(depth). eg:
while (!list.isEmpty() && readCount < 10 )
This will eliminate the chance of running the code to infinity(in case of circular reference).

Categories