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).
Related
Hello can someone help me? The point of the homework is to read a file then create another file where it replaces all of the words "is" with "was", i have all this done but I am also not sopposed to replace words that have"is" in them, for example: "this, isthmus".
import java.io.*;
import java.util.*;
public class WordChange {
public static void main(String[]args) throws Exception {
FileReader fr = null;
FileWriter fw = null;
try
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the name of the text file: ");
String fileName=keyboard.nextLine();
File file = new File(fileName);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
String replacedtext=oldtext.replaceAll("is ","was ");
FileWriter writer = new FileWriter("output.txt");
writer.write(replacedtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
just a guess here but instead of
String replacedtext=oldtext.replaceAll("is ","was ");
would this work
String replacedtext=oldtext.replaceAll(" is "," was ");
Im just guessing let me know if it works
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;
}
This question already has answers here:
Standard concise way to copy a file in Java?
(16 answers)
Closed 8 years ago.
I am trying to read a file and write to another file it is not working I invoke the method from the main
public boolean copy(String inputPlayList, String outputPlayList, int numberOfMunites)
{
String start1 = "#EXTINF:";
String afterNum = ";";
try
{
declaring those variable that I would use to pass the method
File fInput, fOutput;
String s;
String a;
assigning those variable to the method
fInput = new File(inputPlayList);
fOutput = new File(outputPlayList);
// Now I am using bufferedRead and BufferedWriter to read and write in a file
BufferedReader br = new BufferedReader(new FileReader(new File(inputPlayList)));
BufferedWriter out = new BufferedWriter(new BufferedWriter(new FileWriter(outputPlayList)));
// creating a while saying while the line is not finish contunue to read
while((s = br.readLine())!= null)
{
if(s.contains(start1)) {
String numberInString = s.substring(start1.length(), s.indexOf(afterNum));
numberOfMunites+= Integer.getInteger(numberInString);
}
// when it is finsh close the file.
out.write(s);
}
out.close();
System.out.println("donne");
}catch ( IOException e)
{
System.err.println("the is an erro that need to be fixed"+e);
}
return false;
}
}
Simplest way in java:
File input = new File("input/file");
File output = new File("output/file");
InputStream is = new FileInputStream(input); // can be any input stream, even url.open()
OutputStream os = new FileOutputStream(output);
byte[] buffer = new byte[4096];//
int read = 0;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
is.close();
os.close();
Try Apache Commons IO Utils.
FileUtils.copyFile(new File(inputPlayList),new File(outputPlayList));
Here it is, but I don't understand the meaning of the numberOfminutes argument, what is it for? I've changed implementation to return calculated number of minutes from the function.
import java.io.*;
public class Main {
public static void main(String[] args) {
System.out.println(copy("D:\\1.txt", "D:\\2.txt", 0)); //returns the calculated number of minutes
}
public static int copy(String inputPlayList, String outputPlayList, int numberOfMinutes) {
String start1 = "#EXTINF:";
String afterNum = ";";
try {
BufferedReader br = new BufferedReader(new FileReader(new File(inputPlayList)));
PrintWriter out = new PrintWriter(new FileWriter(outputPlayList));
String s;
while ((s = br.readLine()) != null) {
if (s.contains(start1)) {
String numberInString = s.substring(start1.length(), s.indexOf(afterNum));
numberOfMinutes += Integer.parseInt(numberInString);
}
out.println(s);
}
out.close();
} catch (IOException e) {
System.err.println("Exception" + e);
}
return numberOfMinutes;
}
}
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.
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();
}