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();
}
Related
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.
I have this code to read from a text file and then modify it. Then write the modified content to another text file.
I am getting a null pointer exception at out.write(read); And also, not all lines are being written, can some one help me please. Thank you
import java.util.*;
import java.io.*;
public class File
{
BufferedReader in;
BufferedWriter out;
String read;
public File()
{
try {
in = new BufferedReader(new FileReader("myFile.txt"));
Scanner scan = new Scanner(in);
out = new BufferedWriter(new FileWriter("output.txt"));
while (scan.hasNext()) {
read = in.readLine();
//Write codes to modify file here
//___codes not written yet______//
out.write(read);
scan.next();
System.out.println("file output: " + read);
}
out.close();
in.close();
} catch (IOException e) {
System.out.println("There was a problem:" + e);
}
}
public static void main(String[] args)
{
File File = new File();
}
}
try
while((read = in.readLine()) != null)
instead of
while (scan.hasNext())
need to change :while((read = in.readLine()) != null).
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;
}
I have a srt file like below and I want to remove blank line : in line no 3
**
1
Line1: 00:00:55,888 --> 00:00:57,875.
Line2:Antarctica
Line3:
Line4:2
Line5:00:00:58,375 --> 00:01:01,512
Line6:An inhospitable wasteland.
**
FileInputStream fin = new FileInputStream("line.srt");
FileOutputStream fout = new FileOutputStream("m/line.srt");
int i = 0;
while(((i =fin.read()) != -1)){
if(i != 0)
fout.write((byte)i);
}
There you go. Steps:
1) FileInputStream fin = new FileInputStream("line.srt"); this is to get the file to a bufferedreader in the next step
2) BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); get the text file to a buffereader
3) PrintWriter out = new PrintWriter("newline.srt"); use a print writer to write the string of every line in the new text file
4) String line = reader.readLine(); read next line
5) while(line != null){
if (!line.trim().equals("")) { check that line is not null and that line is not empty
6) out.println(line); write line (not empty) to the output .srt file
7) line = reader.readLine(); get new line
8) out.close(); close PrintWriter in the end...
import java.io.*;
class RemoveBlankLine {
public static void main(String[] args) throws FileNotFoundException, IOException{
FileInputStream fin = new FileInputStream("line.srt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
PrintWriter out = new PrintWriter("newline.srt");
int i = 0;
String line = reader.readLine();
while(line != null){
if (!line.trim().equals("")) {
out.println(line);
}
line = reader.readLine();
}
out.close();
}
}
INPUT:
**
1
00:00:55,888 --> 00:00:57,875.
Antarctica
2
00:00:58,375 --> 00:01:01,512
An inhospitable wasteland.
**
OUTPUT:
**
1
00:00:55,888 --> 00:00:57,875.
Antarctica
2
00:00:58,375 --> 00:01:01,512
An inhospitable wasteland.
**
By the way, make sure you are clear when you ask your questions, because the way you state your problem I assumed Line1, Line2, etc are part of your input file, and I have prepared another solution which I had to change... Make sure you are clear and precise so that you get the proper answers !
You can try something like :
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("line.srt"));
bw = new BufferedWriter(new FileWriter("m/line.srt"));
for(String line; (line = br.readLine()) != null; ) {
if(line.trim().length() == 0) {
continue;
} else {
bw.write(line);
bw.newLine();
}
}
bw.flush();
bw.close();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
hope this help
public static void main(String[] args) throws FileNotFoundException, IOException {
Path myPath = Paths.get("e:\\", "1.txt");
List<String> ls ;
ls = Files.readAllLines(myPath, StandardCharsets.US_ASCII);
PrintWriter out = new PrintWriter("e:\\2.txt");
for (int i = 0; i < ls.size(); i++) {
String []temp = ls.get(i).split(":");
if(temp.length>1) {
out.println(ls.get(i));
}
}
out.close();
}
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.