Can't write all list to the file - java

I have an ArrayList list of some lines from text file. I am trying to find these lines in a text file, if I find it I want to write it to another text file and delete it from the original file.
I wrote a code for that, it is working but not for the whole list, sometimes take one line and sometimes take more. and give me this message:
1 R101 100850 0
Exception caught : java.io.IOException: Stream closed
static void moveLines(ArrayList posList, int topic) {
//=======================To read lines=======
File inputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\TestData\\topic\\" + "Test" + topic + ".txt");
File outputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\TestData\\topic\\" + "Training" + topic + ".txt");
try {
FileReader fr = new FileReader(inputFile);
BufferedReader br = new BufferedReader(fr);
FileWriter fr1 = new FileWriter(outputFile);
BufferedWriter writer = new BufferedWriter(fr1);
String line;
int count = 1;
int z = 1;
while ((line = br.readLine()) != null) {
// System.out.println(z++ + ": ");
String subLine = line.substring(5, line.length() - 2);
// System.out.println(subLine);
if (posList.contains(subLine)) {
System.out.println(count++ + " " + line);
fr1.write(line);
fr1.write("\n");
fr1.flush();
fr.close();
removeLineFromFile(inputFile.getAbsolutePath(), line);
}
}
br.close();
fr1.close();
writer.close();
} catch (Exception e) {
System.out.println("Exception caught : " + e);
}
}
static void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Can someone help me please?

String subLine = line.substring(5, line.length() - 2);
You are hard coding to take substring from index 5.
What happens when the length of line is less than 5? have a check if the line's length is less than 5 and only then proceed.
Also why are catching with 'Exception' ? try catching with a lower level exception like ArrayIndexOutOfBoundsException etc.

Thank you all for your help.
I figure out the problem, it was because I delete the file and create it again from temp file. in that case I lose the pointer to the file.
This is the code after I fix it if someone interested.
static void moveLines(ArrayList posList, int topic) {
//=======================To read lines=======
File inputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\Data1\\topic\\" + "Test" + topic + ".txt");
File outputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\Data1\\topic\\" + "Training" + topic + ".txt");
try {
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
String subLine = line.substring(5, line.length() - 2);
if (posList.contains(subLine)) {
System.out.println(count++ + " " + line);
bufferedReader.close();
fileReader.close();
bufferedWriter.write(line+"\n");
bufferedWriter.flush();
bufferedReader = removeLineFromFile(inputFile.getAbsolutePath(), line);
}
}
bufferedWriter.close();
fileWriter.close();
bufferedReader.close();
fileReader.close();
} catch (Exception e) {
System.out.println("Exception caught : " + e);
}
}
static BufferedReader removeLineFromFile(String file, String lineToRemove) {
BufferedReader bufferedReader = null;
try {
File inFile = new File(file);
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
bw.write(line+"\n");
bw.flush();
}
}
bw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return null;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}
FileReader fileReader = new FileReader(inFile);
bufferedReader = new BufferedReader(fileReader);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return bufferedReader;
}

Related

I have a filewriter method that only ouputs to the file when i close it

String filePath = "Seat";
static void modifyFile(String filePath, String oldString, String newString) {
File fileToBeModified = new File(filePath);
String oldContent = "";
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(fileToBeModified));
//Reading all the lines of input text file into oldContent
String line = reader.readLine();
while (line != null) {
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
//Replacing oldString with newString in the oldContent
String newContent = oldContent.replaceAll(oldString, newString);
//Rewriting the input text file with newContent
writer = new BufferedWriter(new FileWriter(fileToBeModified));
writer.write(newContent);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//Closing the resources
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This method is meant to change a certain line in a file the method itself works when run but it only changes the line when i close the program which is when it closes the writer, i looked it up and add writer.flush() earlier on in the code to see if that would work but i still have the same problem
You are trying to read from and write to the same file.
You cannot do both operations at the same time as the file will get locked. close the reader and then do the write operation.

Rewrite a specific line in a txt file

I was trying to rewrite a line that contains student details in a txt file. There will be a list of students' detail in the file, for example:
Name1,10
Name2,20
Name3,30
I tried to rewrite Name2,20 to Name2,13 using a BufferedReader to find the line with Name2. And a BufferedWriter to replace the line with new text, but it turns out the code will write my whole txt file to null.
Here's my code:
String lineText;
String newLine = "Name,age";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(path,false));
while ((lineText = br.readLine()) != null){
System.out.println(">" + lineText);
String studentData[] = lineText.split(",");
if(studentData[0].equals(Name2)){
bw.write(newLine);
}
System.out.println(lineText);
}
br.close();
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
Can anyone please tell me how to rewrite a specific line in txt file?
Easiest way is to read the entire file, and store it in a variable. Replacing the line in question while reading the current file.
Something like:
String lineText;
String newLine = "Name,age";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(path,false));
String currentFileContents = "";
while ((lineText = br.readLine()) != null){
System.out.println(">" + lineText);
String studentData[] = lineText.split(",");
if(studentData[0].equals("Name2")){
currentFileContents += newLine;
} else {
currentFileContents += lineText;
}
}
bw.write(currentFileContents);
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}

How to write in existing file from list using Java by removing duplicate data?

I want to write in file that exists.
My data is in the form of java list.
Here is a sample of data :
snmp,192.168.20.1,cloud,
snmp,192.168.20.2,cloud,
I want to add line snmp,192.168.20.1,cloud123 in the file.
It should update existing file content i.e.(snmp,192.168.20.1,cloud) by new contents given.
And if provided contents different from contents of file then append it to file?
Here is my workaround---
String tempFile = RunMTNew.instdir + "/var/";
File tempFileName = new File(tempFile+"hosts.tempFile");
try{
if(!tempFileName.exists()) {
tempFileName.createNewFile();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
catch ( IOException ioe){
ioe.printStackTrace();
System.out.println("Exception occured while creating temp file");
}
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
PrintWriter tempoutfile= null;
while((line = bufferedReader.readLine()) != null) {
System.out.println("line before if "+ line);
if(line!=null || (line = line.trim()) != "" ){
System.out.println("line at start of while" + line);
String[] lineFromFile = line.split(",");
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)));
ListIterator atwlist = arraytowrite.listIterator();
String lineToWriteInFile = "";
while (atwlist.hasNext()) {
ArrayList atwlistline = (ArrayList) atwlist.next();
System.out.println("array" + atwlistline);
String lineToAdd = atwlistline.toString();
lineToWriteIfNotFound = lineToAdd;
System.out.println("After converting to string line is" + lineToAdd);
System.out.println("lineFromFile contents are "+ lineFromFile[1]);
if(lineToAdd.contains(lineFromFile[1])){
lineToWriteInFile = lineToAdd;
}
else{
lineToWriteInFile = line;
}
}
try{
tempoutfile = new PrintWriter(new BufferedWriter(new FileWriter(tempFileName, true)));
System.out.println("writing in file" +lineToWriteInFile);
tempoutfile.write(lineToWriteInFile);
tempoutfile.write("\n");
}catch(IOException ioe){
ioe.printStackTrace();
System.out.println("Exception occured while writing in tempFile");
}
tempoutfile.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Exception occured in outer try block");
}
}//end of if
}// end of while
try{
FileReader tempfileReader = new FileReader(tempFile+"hosts.tempFile");
BufferedReader tempBufferedReader = new BufferedReader(tempfileReader);
FileWriter fosFinal = new FileWriter(filename);
PrintWriter outFinal = new PrintWriter(fosFinal);
while((line = tempBufferedReader.readLine()) != null) {
System.out.println("line from tempfile to write in main " + line);
outFinal.write(line);
}
}catch(IOException ie){
ie.printStackTrace();
System.out.println("Exception occured while reading from temp and write into main file");
}
Use temp file to store temporarily contents of file.
Here is a code :
ListIterator atwlist = arraytowrite.listIterator();
while (atwlist.hasNext()) {
ArrayList atwlistline = (ArrayList) atwlist.next();
ListIterator atwlistlineL = atwlistline.listIterator();
while (atwlistlineL.hasNext()) {
firstWriter.write((String) atwlistlineL.next());
firstWriter.write(",");
}
//firstWriter.write("\n");
System.out.println(atwlistline);
}
firstWriter.close();
//Write original file contents to another file i.e. tempFile2
try{
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
String line = "";
while((line = bufferedReader.readLine()) != null) {
secondWriter.write(line);
secondWriter.write("\n");
}
secondWriter.close();
bufferedReader.close();
}catch(IOException ie){
ie.printStackTrace();
System.out.println("Exception occured while reading from main file");
}
//check and remove duplicate entries from file
try{
FileReader singleDeviceReader = new FileReader(file1Path);
FileReader duplicateDeviceReader = new FileReader(file2Path);
finalWriter = new PrintWriter(filename);
BufferedReader bufferedReader1 = new BufferedReader(singleDeviceReader);
BufferedReader bufferedReader2 = new BufferedReader(duplicateDeviceReader);
String line1 = null;
String line2 = null;
boolean fileWriteFlag = false;
String ifNotFind = "";
while((line1 = bufferedReader1.readLine())!=null){
String[] line1Split = line1.split(",");
ifNotFind = line1;
while((line2 = bufferedReader2.readLine())!=null){
String[] line2Split = line2.split(",");
if (line2Split[1].equals(line1Split[1])){
finalWriter.write(line1);
finalWriter.write("\n");
fileWriteFlag = true;
}
else {
finalWriter.write(line2);
finalWriter.write("\n");
}
}
}
if(!fileWriteFlag){
finalWriter.write(ifNotFind);
}
finalWriter.close();
bufferedReader1.close();
bufferedReader2.close();
File t1 = new File (file1Path);
File t2 = new File (file1Path);
if (t1.exists()){
t1.delete();
}
if (t2.exists()){
t2.delete();
}
}catch (IOException ioe ){
ioe.printStackTrace();
System.out.println("Exception occured while reading both temp files");
}
Instead of checking and comparing the content from the file I suggest you create list with unique items. Which will save your time to parse the file content and update operations on file and your code as well
First get all the existing data set to a list. now iterate your new list(which need to append) using a for loop and get a inner loop and check condition and add/skip.
Pseudo code:
List my_existing_list;
List my_new_list;
foreach(my_new_list){
foreach(my_existing_list){
if(equal to an existing item){
//skip
}else{
//append to file
}
}
}

Writing a file to another file

When I tried to run OUT.TXT it was alwasy empty. Can you please assist me in finding out why? Also SPY.LOG lines are not ordinary, can you assit with a way to fix those lines also?
package burak;
import java.io.*;
public class Yucal {
public static void main(String [] args) {
String fileName = "spy.log";
String line;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
try{
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(line);
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
System.out.printf("%65s\n", line);
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'"); }
}
Few changes
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
while ((line = bufferedReader.readLine()) != null) {
try {
out.write(line);
out.write("\n");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.printf("%65s\n", line);
}
out.close();
bufferedReader.close();
The mistake was you've opened FileWriter fstream = new FileWriter("out.txt"); within while loop. It must be outside.
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
try{
>FileWriter fstream = new FileWriter("out.txt");**
>BufferedWriter out = new BufferedWriter(fstream);**
<snip>
Everytime you open your file and write one line. Then close it. Next time you open it, you overwrite the previous contents of the file. You should probably move the lines marked with > outside the while loop.
The last line of your file spy.log might be empty.
Additionally move all close statements to finally block.
You might also need to handler some IO exceptions when you close these streams.
Hope this helps.

Reading/Writing Files in Java and Adding Line Numbers

I have the following assignment to complete:
Wrote a program that reads a file and writes a copy of the file to another file with line numbers inserted.
So far, I wrote the code that is posted below. This code reads and copies the text to another file, but I cannot figure out how to number each line in the new text file. Can someone please advise me on how to do so?
import java.io.*;
class FileCopy
{
public static void main(String[] args)
{
try
{
File fileIn = new File("Assign4.txt");
File fileOut = new File("target.txt");
FileInputStream streamIn = new FileInputStream(fileIn);
FileOutputStream streamOut = new FileOutputStream(fileOut);
int c;
while ((c = streamIn.read()) != -1)
{
streamOut.write(c);
}
streamIn.close();
streamOut.close();
}
catch (FileNotFoundException e)
{
System.err.println("FileCopy: " + e);
}
catch (IOException e)
{
System.err.println("FileCopy: " + e);
}
}
}
Thank you, I appreciate your help.
I will suggest BufferedReader (for sure) and PrintWriter. PrintWriter is a richer API compared to BufferedWriter.
You can you BufferedReader and BufferedReader to read and write text file:
BufferedReader br = new BufferedReader(new FileReader("Assign4.txt"));
BufferedWriter writer = new BufferedWriter( new FileWriter("target.txt"));
try {
int count = 1;
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(count++);
sb.append(line);
sb.append("\n");
writer.write(line);
line = br.readLine();
}
} finally {
br.close();
writer.close();
}

Categories

Resources