How to update a string with new value in java? - java

I am new to java and working on file operations. I have this input and modify text files as follows:
input.txt: contains id,firstname,lastname
1000:Mark,Peters,3.9
modify.txt: contains id,oldvalue:newvalue
1000,Mark:John
I am supposed to search the id and make the updations accordingly. So in modify.txt file I have an id and old value which is to be replaced with new value in the input.txt
So after modification, my input.txt line output should be printed as:
1000:John,Peters,3.9
I have written the following code, but I am not sure how to proceed with updations. However, I have managed to read the files and split it and get the id.
public static void main(String[] args) {
try {
BufferedReader file1 = new BufferedReader(new FileReader(new File("src/input.txt")));
BufferedReader file2 = new BufferedReader(new FileReader(new File("src/modify.txt")));
String str1 = file1.readLine();
String input[] = str1.split(":");
int id1 = Integer.parseInt(input[0]);
System.out.println(str1);
System.out.println(id1);
String str2 = file2.readLine();
String modify[] = str2.split(",");
int id2 = Integer.parseInt(modify[0]);
System.out.println(str2);
System.out.println(id2);
file1.close();
file2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Can anyone help me with this? Thanks. Appreciate your help.

You can read the line in modify.txt file and split the line using regex [,:]. It will split the line into separate parts like id, firstName and lastName etc.
After read the each line in input.txt file and and split the each line using the regex [,:]. And compare the first element in the list with element in the list created from modify.txt file. if the element is equals replace the line with the new data from list created from modify.txt file.
public static void main(String[] args) {
try {
BufferedReader f1 = new BufferedReader(new FileReader(new File("src/input.txt")));
BufferedReader f2 = new BufferedReader(new FileReader(new File("src/modify.txt")));
String regex = "[,:]";
StringBuffer inputBuffer = new StringBuffer();
String line;
String[] newLine = f2.readLine().split(regex);
while ((line = f1.readLine()) != null) {
String[] data = line.split(regex);
if (data[0].equals(newLine[0])) {
line = line.replace(newLine[1], newLine[2]);
}
inputBuffer.append(line);
inputBuffer.append(System.lineSeparator());
}
f1.close();
f2.close();
FileOutputStream fileOut = new FileOutputStream("src/input.txt");
fileOut.write(inputBuffer.toString().getBytes());
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Simplest way to concatenate multi lines of text in java through File Handling

I tried concatenating 2 lines of text in a given text file and printing the output to the console. My code is very complicated, is there a simpler method to achieve this by using FileHandling basic concepts ?
import java.io.*;
public class ConcatText{
public static void main(String[] args){
BufferedReader br = null;
try{
String currentLine;
br = new BufferedReader(new FileReader("C:\\Users\\123\\Documents\\CS105\\FileHandling\\concat.file.text"));
StringBuffer text1 = new StringBuffer (br.readLine());
StringBuffer text2 = new StringBuffer(br.readLine());
text1.append(text2);
String str = text1.toString();
str = str.trim();
String array[] = str.split(" ");
StringBuffer result = new StringBuffer();
for(int i=0; i<array.length; i++) {
result.append(array[i]);
}
System.out.println(result);
}
catch(IOException e){
e.printStackTrace();
}finally{
try{
if(br != null){
br.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
The text file is as follows :
GTAGCTAGCTAGC
AGCCACGTA
the output should be as follows (concatenation of the text file Strings) :
GTAGCTAGCTAGCAGCCACGTA
If you are using java 8 or newer, the simplest way would be:
List<String> lines = Files.readAllLines(Paths.get(filePath));
String result = String.join("", lines);
If you are using java 7, at least you can use try with resources to reduce the clutter in the code, like this:
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
StringBuffer text1 = new StringBuffer (br.readLine());
StringBuffer text2 = new StringBuffer(br.readLine());
// ...
}catch(IOException e){
e.printStackTrace();
}
This way, resources will be autoclosed and you don't need to call br.close().
Short answer, there is:
public static void main(String[] args) {
//this is called try-with-resources, it handles closing the resources for you
try (BufferedReader reader = new BufferedReader(...)) {
StringBuilder stringBuilder = new StringBuilder();
String line = reader.readLine();
//readLine() will return null when there are no more lines
while (line != null) {
//replace any spaces with empty string
//first argument is regex matching any empty spaces, second is replacement
line = line.replaceAll("\\s+", "");
//append the current line
stringBuilder.append(line);
//read the next line, will be null when there are no more
line = reader.readLine();
}
System.out.println(stringBuilder);
} catch (IOException exc) {
exc.printStackTrace();
}
}
First of all read on try with resources, when you are using it you don't need to close manually resources(files, streams, etc.), it will do it for you. This for example.
You don't need to wrap read lines in StringBuffer, you don't get anything out of it in this case.
Also read about the methods provided by String class starting with the java doc - documentation.

How to read a specific word in text file and use a condition statement to do something

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");
}
}
}
}

How to delete a line from text line by id java

How to delete a line from a text file java?
I searched everywhere and even though I can't find a way to delete a line.
I have the text file: a.txt
1, Anaa, 23
4, Mary, 3
and the function taken from internet:
public void removeLineFromFile(Long id){
try{
File inputFile = new File(fileName);
File tempFile = new File("C:\\Users\\...myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = Objects.toString(id,null);
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
String trimmLine[] = trimmedLine.split(" ");
if(!trimmLine.equals(lineToRemove)) {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
}catch (IOException e){
e.printStackTrace();
}
}
where the fileName is the path for a.txt.
I have to delete the line enetering the id.That's why I split the trimmedLine. At the end of execution I have 2 files, the a.txt and myTempFile both having the same lines(the ones from beginning). Why couldn't delete it?
If I understand your question correctly, you want to delete the line whose id matches with the id passed in the removeLineFromFile method.
To make your code work, only few changes are needed.
To extract the id, you need to split using both " " and ","
i.e.
String trimmLine[] = trimmedLine.split(" |,");
where | is the regex OR operator.
See Java: use split() with multiple delimiters.
Also, trimmLine is an array, you can't just compare trimmLine with lineToRemove. You first need to extract the first part which is the id from trimmLine. I would suggest you to look at the working of split method if you have difficulty in understanding this. You can have a look at How to split a string in Java.
So, extract the id which is the first index of the array trimmLine here using:
String part1 = trimmLine[0];
and then compare part1 with lineToRemove.
Whole code looks like:
public void removeLineFromFile(Long id){
try{
File inputFile = new File(fileName);
File tempFile = new File("C:\\Users\\...myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = Objects.toString(id,null);
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
String trimmLine[] = trimmedLine.split(" |,");
String part1 = trimmLine[0];
if(!part1.equals(lineToRemove)) {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
}catch (IOException e){
e.printStackTrace();
}
}

Unable to compare last word in the file

I have been trying to compare the input file with the database file. The code compares the files and outputs the words from the input file(test.txt) that are present in the database file(db.txt). But however I am not getting the last word from the input file in the output.
test.txt contains:
There is a book on the table
db.txt contains:
book
the
table
Thus here I am not getting table in the output.
public static void main(String[] args) {
try {
File file = new File("G:\\Project\\test.txt");
File file2 = new File("G:\\Project\\db.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
StringTokenizer st = new StringTokenizer(stringBuffer.toString()," ");
while (st.hasMoreTokens())
{
String word=st.nextToken();
BufferedReader br = new BufferedReader(new FileReader(file2));
String lin;
while((lin=br.readLine())!=null){
{ if(word.equalsIgnoreCase(lin))
System.out.println(word);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Output received:
book
the
What is it that I am doing wrong here?
You are appending newline character to stringbuffer and that is causing this issue.
Remove below line from your code and try, it will work.
stringBuffer.append("\n");

Java - Create String Array from text file [duplicate]

This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 1 year ago.
I have a text file like this :
abc def jhi
klm nop qrs
tuv wxy zzz
I want to have a string array like :
String[] arr = {"abc def jhi","klm nop qrs","tuv wxy zzz"}
I've tried :
try
{
FileInputStream fstream_school = new FileInputStream("text1.txt");
DataInputStream data_input = new DataInputStream(fstream_school);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
String[] itemsSchool = str_line.split("\t");
}
}
}
catch (Exception e)
{
// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Anyone help me please....
All answer would be appreciated...
If you use Java 7 it can be done in two lines thanks to the Files#readAllLines method:
List<String> lines = Files.readAllLines(yourFile, charset);
String[] arr = lines.toArray(new String[lines.size()]);
Use a BufferedReader to read the file, read each line using readLine as strings, and put them in an ArrayList on which you call toArray at end of loop.
Based on your input you are almost there. You missed the point in your loop where to keep each line read from the file. As you don't a priori know the total lines in the file, use a collection (dynamically allocated size) to get all the contents and then convert it to an array of String (as this is your desired output).
Something like this:
String[] arr= null;
List<String> itemsSchool = new ArrayList<String>();
try
{
FileInputStream fstream_school = new FileInputStream("text1.txt");
DataInputStream data_input = new DataInputStream(fstream_school);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
itemsSchool.add(str_line);
}
}
arr = (String[])itemsSchool.toArray(new String[itemsSchool.size()]);
}
Then the output (arr) would be:
{"abc def jhi","klm nop qrs","tuv wxy zzz"}
This is not the optimal solution. Other more clever answers have already be given. This is only a solution for your current approach.
This is my code to generate random emails creating an array from a text file.
import java.io.*;
public class Generator {
public static void main(String[]args){
try {
long start = System.currentTimeMillis();
String[] firstNames = new String[4945];
String[] lastNames = new String[88799];
String[] emailProvider ={"google.com","yahoo.com","hotmail.com","onet.pl","outlook.com","aol.mail","proton.mail","icloud.com"};
String firstName;
String lastName;
int counter0 = 0;
int counter1 = 0;
int generate = 1000000;//number of emails to generate
BufferedReader firstReader = new BufferedReader(new FileReader("firstNames.txt"));
BufferedReader lastReader = new BufferedReader(new FileReader("lastNames.txt"));
PrintWriter write = new PrintWriter(new FileWriter("emails.txt", false));
while ((firstName = firstReader.readLine()) != null) {
firstName = firstName.toLowerCase();
firstNames[counter0] = firstName;
counter0++;
}
while((lastName= lastReader.readLine()) !=null){
lastName = lastName.toLowerCase();
lastNames[counter1]=lastName;
counter1++;
}
for(int i=0;i<generate;i++) {
write.println(firstNames[(int)(Math.random()*4945)]
+'.'+lastNames[(int)(Math.random()*88799)]+'#'+emailProvider[(int)(Math.random()*emailProvider.length)]);
}
write.close();
long end = System.currentTimeMillis();
long time = end-start;
System.out.println("it took "+time+"ms to generate "+generate+" unique emails");
}
catch(IOException ex){
System.out.println("Wrong input");
}
}
}
You can read file line by line using some input stream or scanner and than store that line in String Array.. A sample code will be..
File file = new File("data.txt");
try {
//
// Create a new Scanner object which will read the data
// from the file passed in. To check if there are more
// line to read from it we check by calling the
// scanner.hasNextLine() method. We then read line one
// by one till all line is read.
//
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//store this line to string [] here
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner scanner = new Scanner(InputStream);//Get File Input stream here
StringBuilder builder = new StringBuilder();
while (scanner.hasNextLine()) {
builder.append(scanner.nextLine());
builder.append(" ");//Additional empty space needs to be added
}
String strings[] = builder.toString().split(" ");
System.out.println(Arrays.toString(strings));
Output :
[abc, def, jhi, klm, nop, qrs, tuv, wxy, zzz]
You can read more about scanner here
You can use the readLine function to read the lines in a file and add it to the array.
Example :
File file = new File("abc.txt");
FileInputStream fin = new FileInputStream(file);
BufferedReader reader = new BufferedReader(fin);
List<String> list = new ArrayList<String>();
while((String str = reader.readLine())!=null){
list.add(str);
}
//convert the list to String array
String[] strArr = Arrays.toArray(list);
The above array contains your required output.

Categories