This question already has answers here:
Reading and Writing to a .txt file in Java
(4 answers)
Closed 6 years ago.
This is my code, I can't make it work properly, it gets just the last line from 3 lines total from the first text file and capitalize only that, and I cant figure out why
import java.util.Scanner;
import java.io.*;
public class AllCapitals {
public static void main(String[] args) {
String readLine;
String inFilePath = "/home/file.txt";
String outFilePath = "/home/newFile.txt";
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inFilePath))) {
while ((readLine = bufferedReader.readLine()) != null) {
readLine.toUpperCase();
String upperC = readLine.toUpperCase();
System.out.println(upperC);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFilePath), "utf-8"))) {
writer.write(upperC);
}
}
} catch (IOException e) {
System.out.println("Error.");
e.printStackTrace();
}
}
}
EDIT: Forgot to say the functionallity.
I need to read 3 lines from a normal text file that goes like that
Hello.
How are you ?
Good, thank you !
And the output should be in all CAPS, but I get only the last line "GOOD THANK YOU"
That's because you recreate the output file in each iteration while reading lines from the first.
Create the output file once before you start reading, for example:
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inFilePath));
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFilePath), "utf-8"))
) {
while ((readLine = bufferedReader.readLine()) != null) {
String upperC = readLine.toUpperCase();
System.out.println(upperC);
writer.write(upperC);
writer.write(System.lineSeparator());
}
} catch (IOException e) {
System.out.println("Error.");
e.printStackTrace();
}
Some other improvements:
Removed a pointless line readLine.toUpperCase(); that did nothing
Add a linebreak for each line, otherwise all the uppercased content would be on the same line
Related
This question already has answers here:
Modify the content of a file using Java
(6 answers)
Closed 3 years ago.
I am new at java and teacher gave us a project homework. I have to implement read the file line by line, slice the lines at the comma and store the parts at a multidimensional array, change the specific part of the line (I want to change the amount).
The given file:
product1,type,amount
product2,type,amount
product3,type,amount
product4,type,amount
product5,type,amount
I tried this code but I couldn't change the specific part.
BufferedReader reader;
int j=0;
int i=0;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
j++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
String total_length[][]=new String[j][3];
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
String[] item = line.split(",");
total_length[i][0]=item[0];
total_length[i][1]=item[0];
total_length[i][2]=item[0];
i++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Thanks a lot!
First, you need to read the file. There are plenty of way to do it, one of them is:
BufferedReader s = new BufferedReader(new FileReader("filename"));
Which allows you to do s.readLine() to read it line by line.
You can use a while loop to read it until the end. Note that readLine will return null if you reach the end of the file.
Then, for each line, you want to split them with the coma. You can use the split method of Strings:
line.split(",");
Putting it all together, and using a try-catch for IOException, you get:
List<String[]> result = new ArrayList<>();
try (BufferedReader s = new BufferedReader(new FileReader("filename"))) {
String line;
while ((line = s.readLine()) != null) {
result.add(line.split(","));
}
} catch (IOException e) {
// Handle IOExceptions here
}
If you really need a two dimensional array at the end, you can do:
String[][] array = new String[0][0];
array = result.toArray(array);
You then have read the file in the format you wanted, you can now modify the data that you parsed.
What i'm trying to do, is to replace a symbol in a file text which contains over 4000 lines but using the below code, after the program ends, it only remain 500 lines. Why is this file truncated? How to solve this?
This is my code:
ArrayList<String> arrayList = new ArrayList<>();
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {System.err.println(e);}
}
} catch (Exception e) {e.printStackTrace();}
Thanks in advance!
new BufferedWriter(new FileWriter(file)) clear file.
You should open it only once. Also you reading and writing to the same file. You should use different files.
Like this
try (FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
bw.write(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
You are writing to the same file while you are reading it. This won't work. Once you start writing, the file becomes empty (plus whatever you've written), so subsequent reads will report end-of-file. Your ~500 lines will be buffered input from the first read.
One solution is to do all the reading first, before opening the file again for writing:
Array<String> arrayList = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
while ((String line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {
System.err.println(e);
}
Here, first the program slurps the file into a List<String>, fixing the lines as it goes. Then it writes all the lines back out to the file.
There are circumstances in which this model is appropriate. For example, you might be building a non-linear data structure from the file content. Or you might need to see the last line before you can modify earlier lines (and be unable to re-open the data source from the start).
However I'd suggest a method that's more thrifty with memory. You don't need to keep all those lines in memory. You can read one line, fix it up, then forget about it. But to do this, you'll need to write to a second file.
String filein = "inputfile";
String fileout = filein + ".tmp";
try(
BufferedReader reader = new BufferedReader(new FileReader(filein));
Writer writer = new BufferedWriter(FileWriter(fileout))
) {
while ((String line = bufferedReader.readLine()) != null) {
writer.write(line.replace("þ", "t");
}
}
Files.move(Paths.get(fileout)),
Paths.get(filein),
CopyOption.REPLACE_EXISTING);
I have left out the necessary exception catching -- add back in as required.
I'm new to coding in java. Can anyone help me with my codes? I'm currently making a program where you input a string in a jTextArea, and if the input word(s) matches the one in the text file then it will then do something.
For example: I input the word 'Hey' then it will print something like "Hello" when the input word matches from the text file.
I hope you understand what I mean.
Here's my code:
String line;
String yo;
yo = jTextArea2.getText();
try (
InputStream fis = new FileInputStream("readme.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
)
{
while ((line = br.readLine()) != null) {
if (yo.equalsIgnoreCase(line)) {
System.out.print("Hello");
}
}
} catch (IOException ex) {
Logger.getLogger(ArfArf.class.getName()).log(Level.SEVERE, null, ex);
}
You can not use equals for line because a line contain many words. You have to modify it to search the index of the word in a line.
try (InputStream fis = new FileInputStream("readme.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
line = line.toLowerCase();
yo = yo.toLowerCase();
if (line.indexOf(yo) != -1) {
System.out.print("Hello");
}
line = br.readLine();
}
} catch (IOException ex) {
}
since you are new in java , I would suggest you to take some time to study java 8 which enable to write more clean codes. below is the solution write in java 8, hope can give a kind of help
String yo = jTextArea2.getText();
//read file into stream,
try (java.util.stream.Stream<String> stream = Files.lines(Paths.get("readme.txt"))) {
List<String> matchLines = stream.filter((line) -> line.indexOf(yo) > -1).collect(Collectors.toList()); // find all the lines contain the text
matchLines.forEach(System.out::println); // print out all the lines contain yo
} catch (IOException e) {
e.printStackTrace();
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordFinder {
public static void main(String[] args) throws FileNotFoundException {
String yo = "some word";
Scanner scanner = new Scanner(new File("input.txt")); // path to file
while (scanner.hasNextLine()) {
if (scanner.nextLine().contains(yo)) { // check if line has your finding word
System.out.println("Hello");
}
}
}
}
I am writing a method for my java class. it looks like this so far:
String file_name;
String line;
void addLine(file_name, line){
int line_number;
try {
FileWriter writer = new FileWriter(file_name, true);
PrintWriter out = new PrintWriter(writer);
out.println(line_number + line);
}
catch (IOException e){
System.out.println(e);
}
}
How should I define line_number so it would check how many lines were there in file before I printed out next into it?
int totalLines = 0;
BufferedReader br br = new BufferedReader(new FileReader("C:\\filename.txt"));
String CurrentLine = "";
while ((CurrentLine = br.readLine()) != null) {
++totalLines
}
i think you have to actually read the file by using a bufferedreader. and then keep on incrementing the totalLines till it reach the end of the file
You can count them with a function posted here: Number of lines in a file in Java
They tested it with a 150 MB log file and it seems to be fast.
I want to replace the second line file content, can somebody help please based on the below file format and listener method.
1324254875443
1313131
Paid
0.0
2nd line is long and want to replace to currentTimeMillis().
/************** Pay Button Listener **************/
public class payListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
ArrayList<String> lines = new ArrayList<String>();
String line = null;
try {
FileReader fr = new FileReader("Ticket/" + ticketIDNumber + ".dat");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("Ticket/" + ticketIDNumber + ".dat");
BufferedWriter bw = new BufferedWriter(fw);
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line.replace(System.currentTimeMillis();
lines.add(line);
bw.write(line);
} //end if
} //end try
catch (Exception e) {
} //end catch
} //end while
}//end method
Although this question is very old I'd like to add that this can be achieved much easier since Java 1.7 with java.nio.file.Files:
List<String> newLines = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8)) {
if (line.contains("1313131")) {
newLines.add(line.replace("1313131", ""+System.currentTimeMillis()));
} else {
newLines.add(line);
}
}
Files.write(Paths.get(fileName), newLines, StandardCharsets.UTF_8);
As proposed in the accepted answer to a similar question:
open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.
Based on your implementation, something similar to:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "try.dat";
String tmpFileName = "tmp_try.dat";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line = line.replace("1313131", ""+System.currentTimeMillis());
bw.write(line+"\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
I could suggest to use Apache Commons IO library. There you'll find the class org.apache.commons.io.FileUtils. You can use it:
File file = new File("... your file...");
List<String> lines = FileUtils.readLines(file);
lines.set(1, ""+System.currentTimeMillis());
FileUtils.writeLines(file, lines);
This code reads entire file contents into a List of Strings and changes the second line's content, then writes the list back to the file.
I'm not sure reading and writing the same file simultaneously is a good idea. I think it would be better to read the file line by line into a String array, replace the second line and then write the String array back into the file.