Java file-new updated file appears in a single line - java

I am trying to update a file using Java with new data. Let 's say I have a txt file where I have saved the following data:
id grade
3498 8
2345 9
5444 7
2222 5
So I am trying to update the grade, depending the id the user has typed, but the new (updated) file has the type that follows:
id grade3498 62345 95444 72222 5
and so on....
I can t find the reason why this is not working, I guessed it has something to do with not adding a new line while re-writing the data, but even if I add new line character ("\n") in outobj.write(fileContent.toString()); nothing changes.
Here is a snippet of my code :
public String check(int num) throws RemoteException
{
String textinLine;
String texttoEdit;
File file=new File ("c:\\students.txt");
FileInputStream stream = null;
DataInputStream in =null;
BufferedReader br = null;
try
{
stream = new FileInputStream(file);
in =new DataInputStream(stream);
br = new BufferedReader(new InputStreamReader(in));
StringBuilder fileContent = new StringBuilder();
if ((num>0) && (num<6001))
{
while ((textinLine=br.readLine())!=null)
{
texttoEdit=Integer.toString(num);
System.out.println(textinLine);
String[] parts = textinLine.split(" ");
if (parts.length>0)
{
if (parts[0].equals(texttoEdit))
{
int value = Integer.parseInt(parts[1]);
value-=2;
String edit=Integer.toString(value);
String newLine = "\n"+parts[0]+" "+edit+"\n";
msg="You can pass2";
fileContent.append(newLine);
fileContent.append("\n"); }
else
{
fileContent.append(textinLine);
fileContent.append("\n");
}
}
}
}
in.close();
FileWriter fstream = new FileWriter(file);
BufferedWriter outobj = new BufferedWriter(fstream);
outobj.write(fileContent.toString());
outobj.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Finally, let me say that the new file is rightly edited, which means that if the user enters the id 3498, the grade value would change to 8-2=6, but the new file will be in a single line, as I explained before.

On some OS (typically Windows) you need to use \r\n for a new line. Even better, you can use:
String newLine = System.getProperty("line.separator");
for the line separator which will adjust depending on the platform it is run on.

Related

Remove a Specific Line From text file

I trying to remove a specific line from a file. But I have a problem in deleting a particular line from the text file. Let's said, my text file I want to remove Blueberry in the file following:
Old List Text file:
Chocolate
Strawberry
Blueberry
Mango
New List Text file:
Chocolate
Strawberry
Mango
I tried to run my Java program, when I input for delete and it didn't remove the line from the text file.
Output:
Please delete:
d
Blueberry
Remove:Blueberry
When I open my text file, it keep on looping with the word "Blueberry" only.
Text file:
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
My question is how to delete the specific line from the text file?
Here is my Java code:
String input="Please delete: ";
System.out.println(input);
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
line = reader.readLine();
String inFile="list.txt";
String line = "";
while(!line.equals("x"))
{
switch(line)
{
case "d":
line = reader.readLine();
System.out.println("Remove: " + line);
String lineToRemove="";
FileWriter removeLine=new FileWriter(inFile);
BufferedWriter change=new BufferedWriter(removeLine);
PrintWriter replace=new PrintWriter(change);
while (line != null) {
if (!line.trim().equals(lineToRemove))
{
replace.println(line);
replace.flush();
}
}
replace.close();
change.close();
break;
}
System.out.println(input);
line = reader.readLine();
}
}
catch(Exception e){
System.out.println("Error!");
}
Let's take a quick look at your code...
line = reader.readLine();
//...
while (line != null) {
if (!line.trim().equals(lineToRemove))
{
replace.println(line);
replace.flush();
}
}
Basically, you read the first line of the file and then repeatedly compare it with the lineToRemove, forever. This loop is never going to exit
This is a proof of concept, you will need to modify it to your needs.
Basically, what you need to ensure you're doing, is you're reading each line of the input file until there are no more lines
// All the important information
String inputFileName = "...";
String outputFileName = "...";
String lineToRemove = "...";
// The traps any possible read/write exceptions which might occur
try {
File inputFile = new File(inputFileName);
File outputFile = new File(outputFileName);
// Open the reader/writer, this ensure that's encapsulated
// in a try-with-resource block, automatically closing
// the resources regardless of how the block exists
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
// Read each line from the reader and compare it with
// with the line to remove and write if required
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.equals(lineToRemove)) {
writer.write(line);
writer.newLine();
}
}
}
// This is some magic, because of the compounding try blocks
// this section will only be called if the above try block
// exited without throwing an exception, so we're now safe
// to update the input file
// If you want two files at the end of his process, don't do
// this, this assumes you want to update and replace the
// original file
// Delete the original file, you might consider renaming it
// to some backup file
if (inputFile.delete()) {
// Rename the output file to the input file
if (!outputFile.renameTo(inputFile)) {
throw new IOException("Could not rename " + outputFileName + " to " + inputFileName);
}
} else {
throw new IOException("Could not delete original input file " + inputFileName);
}
} catch (IOException ex) {
// Handle any exceptions
ex.printStackTrace();
}
Have a look at Basic I/O and The try-with-resources Statement for some more details
Reading input from console, reading file and writing to a file needs to be distinguished and done separately. you can not read and write file at the same time. you are not even reading your file. you are just comparing your console input indefinitely in your while loop.In fact, you are not even setting your lineTobeRemoved to the input line. Here is one way of doing it.
Algorithm:
Read the console input (your line to delete) then start reading the file and looking for line to delete by comparing it with your input line. if the lines do not match match then store the read line in a variable otherwise throw this line since you want to delete it.
Once finished reading, start writing the stored lines on the file. Now you will have updated file with one line removed.
public static void main(String args[]) {
String input = "Please delete: ";
System.out.println(input);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String line = reader.readLine();
reader.close();
String inFile = "list.txt";
System.out.println("Remove: " + line);
String lineToRemove = line;
StringBuffer newContent = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(inFile));
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
newContent.append(line);
newContent.append("\n"); // new line
}
}
br.close();
FileWriter removeLine = new FileWriter(inFile);
BufferedWriter change = new BufferedWriter(removeLine);
PrintWriter replace = new PrintWriter(change);
replace.write(newContent.toString());
replace.close();
}
catch (Exception e) {
e.printStackTrace();
}
}

File Writer that puts a number of a line before the line it's about to write

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.

Find and replace in Java using regular expression without changing file format

I've a code which replaces 10:A to 12:A in a text file called sample.txt. Also, the code I've now is changing the file format, which shouldn't. Can someone please let me know how to do the same using regular expression in Java which doesn't change the file format? File has original format as below 10:A 14:Saxws But after executing the code it outputs as 10:A 14:Saxws.
import java.io.*;
import java.util.*;
public class FileReplace
{
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt()
{
try
{
File f1 = new File("sample.txt");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null)
{
if (line.contains("10:A"))
line = line.replaceAll("10:A", "12:A") + System.lineSeparator();
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args)
{
FileReplace fr = new FileReplace();
fr.doIt();
}
}
It looks like your OS or editor is not able to print correctly line separators generated by System.lineSeparator(). In that case consider
reading content of entire file to string (including original line separators), - then replacing part which you are interested in
and writing replaced string back to your file
You can do it using this code:
Path file = Paths.get("sample.txt");
//read all bytes from file (they will include bytes representing used line separtors)
byte[] bytesFromFile = Files.readAllBytes(file);
//convert themm to string
String textFromFile = new String(bytesFromFile, StandardCharsets.UTF_8);//use proper charset
//replace what you need (line separators will stay the same)
textFromFile = textFromFile.replaceAll("10:A", "12:A");
//write back data to file
Files.write(file, textFromFile.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);

Updating a single line on a text file with a Java method

I know previous questions LIKE this one have been asked, but this question has to do with the specifics of the code that I have written. I am trying to update a single line of code on a file that will be permanently updated even when the program terminates so that the data can be brought up again. The method that I am writing currently looks like this (no compile errors found with eclipse)
public static void editLine(String fileName, String name, int element,
String content) throws IOException {
try {
// Open the file specified in the fileName parameter.
FileInputStream fStream = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(
fStream));
String strLine;
StringBuilder fileContent = new StringBuilder();
// Read line by line.
while ((strLine = br.readLine()) != null) {
String tokens[] = strLine.split(" ");
if (tokens.length > 0) {
if (tokens[0].equals(name)) {
tokens[element] = content;
String newLine = tokens[0] + " " + tokens[1] + " "
+ tokens[2];
fileContent.append(newLine);
fileContent.append("\n");
} else {
fileContent.append(strLine);
fileContent.append("\n");
}
}
/*
* File Content now has updated content to be used to override
* content of the text file
*/
FileWriter fStreamWrite = new FileWriter(fileName);
BufferedWriter out = new BufferedWriter(fStreamWrite);
out.write(fileContent.toString());
out.close();
// Close InputStream.
br.close();
}
} catch (IOException e) {
System.out.println("COULD NOT UPDATE FILE!");
System.exit(0);
}
}
If you could look at the code and let me know what you would suggest, that would be wonderful, because currently I am only getting my catch message.
Okay. First off the bat, StringBuilder fileContent = new StringBuilder(); is bad practice as this file could well be larger than the user's available memory. You should not keep much of the file in memory at all. Do this by reading into a buffer, processing the buffer (adjusting it if necessary), and writing the buffer to a new file. When done, delete the old file and rename the secondary to the old one's name. Hope this helps.

Java. How to append text to top of file.txt [duplicate]

This question already has answers here:
Writing in the beginning of a text file Java
(6 answers)
Closed 9 years ago.
I need to add text to beggining of text file via Java.
For example I have test.txt file with data:
Peter
John
Alice
I need to add(to top of file):
Jennifer
It should be:
Jennifer
Peter
John
Alice
I have part of code, but It append data to end of file, I need to make It that added text to top of file:
public static void irasymas(String irasymai){
try {
File file = new File("src/lt/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(irasymai+ "\r\n");
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
I have tried this, but this only deletes all data from file and not insert any text:
public static void main(String[] args) throws IOException {
BufferedReader reader = null;
BufferedWriter writer = null;
ArrayList list = new ArrayList();
try {
reader = new BufferedReader(new FileReader("src/lt/test.txt"));
String tmp;
while ((tmp = reader.readLine()) != null)
list.add(tmp);
OUtil.closeReader(reader);
list.add(0, "Start Text");
list.add("End Text");
writer = new BufferedWriter(new FileWriter("src/lt/test.txt"));
for (int i = 0; i < list.size(); i++)
writer.write(list.get(i) + "\r\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
OUtil.closeReader(reader);
OUtil.closeWriter(writer);
}
}
Thank you for help.
File mFile = new File("src/lt/test.txt");
FileInputStream fis = new FileInputStream(mFile);
BufferedReader br = new BufferedReader(fis);
String result = "";
String line = "";
while( (line = br.readLine()) != null){
result = result + line;
}
result = "Jennifer" + result;
mFile.delete();
FileOutputStream fos = new FileOutputStream(mFile);
fos.write(result.getBytes());
fos.flush();
The idea is read it all, add the string in the front. Delete old file. Create the new file with eited String.
You can use RandomAccessFile to and seek the cursor to 0th position using seek(long position) method, before starting to write.
As explained in this thread
RandomAccessFile f = new RandomAccessFile(new File("yourFile.txt"), "rw");
f.seek(0); // to the beginning
f.write("Jennifer".getBytes());
f.close();
Edit: As pointed out below by many comments, this solution overwrites the file content from beginning. To completely replace the content, the File may have to be deleted and re-written.
The below code worked for me. Again it will obviously replace the bytes at the beginning of the file. If you can certain how many bytes of replacement will be done in advance then you can use this. Otherwise, follow the earlier answers or take a look at here Writing in the beginning of a text file Java
String str = "Jennifer";
byte data[] = str.getBytes();
try {
RandomAccessFile f = new RandomAccessFile(new File("src/lt/test.txt"), "rw");
f.getChannel().position(0);
f.write(data);
f.close();
} catch (IOException e) {
e.printStackTrace();
}

Categories