How to replace particular text in the txt file? - java

Here is my txt file look like.
admin 12345
funny 123
loop 12390
Hi guys. I am trying to replace particular text in my txt file. For example, I want to replace admin's 12345 with something else that I key in in my input2, it means I want to replace the String(pass) that I find out from txt file through scanner. If I use bufferedwritter, the whole content is going to rewrite..How o solve this problem. I am newbie of programming, kindly need you all help.
login.addActionListener(this);
public void actionPerformed(ActionEvent e) {
String inputUser = input1.getText();
String inputPass = input2.getText();
File loginf = new File("oop.txt");
try{
if(e.getSource()==login)
{
Scanner read = new Scanner(new File("oop.txt"));
boolean loginTry = true;
while(read.hasNext())
{
String user = read.next();
String pass = read.next();
if(inputUser.equals(user) && inputPass.equals(pass)){
loginTry=false;
break;
}
}
if(!loginTry)
{
JOptionPane.showMessageDialog(this,"Login Successful");
}

Here is a simple example on how to do what you want!
//Replace a line or word in a file
import java.io.*;
public class BTest
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
// replace a word in a file
//String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
OUTPUT
file.txt
I drink Java
I sleep Java
This is test string 1
This is test string 20000
I did both because the way your txt file is you have more than just a word, you have an ID number of some sorts right next to your users login information. So i would use change line!

Related

How to update a string with new value in 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();
}
}

How can i load data from text file to Jlist in java swing?

I'm learning java. I have trouble when I click JButton to load data from text file to JList, but it notices error "java.lang.NumberFormatException: For input string: """. First of all, I input data from 4 JTextField to JList then save file text. My txt file has content: 1-java-3-4. Someone help me, please. Thank. Here is my code button save and load data:
private void btAddBookActionPerformed(java.awt.event.ActionEvent evt) {
String BookId = txtBookID.getText();
String BookName = txtBookName.getText();
String Quantity = txtQuantity.getText();
String Price = txtPrice.getText();
if(BookId.equals("")|| BookId.equalsIgnoreCase("Type Here") || BookName.equals("")|| BookName.equalsIgnoreCase("Type Here") || Quantity.equals("")|| Quantity.equalsIgnoreCase("Type Here")||Price.equals("")|| Price.equalsIgnoreCase("Type Here")){
txtBookID.setText("Type Here");
txtBookName.setText("Type Here");
txtPrice.setText("Type Here");
txtQuantity.setText("Type Here");
}else{
listmodel.addElement(BookId+"-"+BookName+"-"+Quantity+"-
"+Price);
booklist.setModel(listmodel);
txtBookID.setText("");
txtBookName.setText("");
txtQuantity.setText("");
txtPrice.setText("");
}
private void btLoadDBActionPerformed(java.awt.event.ActionEvent evt) {
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader("BookList.txt"));
int val = Integer.parseInt(br.readLine());
for (int i = 0; i < val; i++) {
String ss = br.readLine();
listmodel.addElement(ss);
}
booklist.setModel(listmodel);
}
catch(Exception e){
System.out.println(""+e);
}
finally{
try{
br.close();
}
catch(Exception e){
System.out.println(""+e);
}
}
}
Looking closer at your code, it seems that you don't need the integer-parsing at all. The problem is that you're reading the file the wrong way. Instead of a for loop, a common idiom for reading a text file line-by-line (when you don't know the exact size of the file) is with a while loop as follows:
br = new BufferedReader(new FileReader("BookList.txt"));
String line;
while ((line = br.readLine()) != null) {
listmodel.addElement(line);
}
booklist.setModel(listmodel);

replacing a string deletes everything in text

I'm trying to write a program for this question: "Write a program that will ask a string and a file name from the user and then removes all the occurrences of that string from that text file."
This is what I have so far:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class RemoveText {
public static void main(String[] args){
//creates a scanner to read the user's file name
Scanner input = new Scanner(System.in);
System.out.println("Enter a file name: ");
String fileName = input.nextLine();
java.io.File file = new java.io.File(fileName);
java.io.File newFile = new java.io.File(fileName);
Scanner stringToRemove = new Scanner(System.in);
System.out.println("Enter a string you wish to remove: ");
String s1 = stringToRemove.nextLine();
//creating input and output files
try {
Scanner inputFile = new Scanner(file);
//reads data from a file
while(inputFile.hasNext()) {
s1 += inputFile.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//supposed to replace each instance of the user input string
//but instead deletes everything on the file and i don't know why
String s2 = s1.replaceAll(s1, "");
try {
PrintWriter output = new PrintWriter(newFile);
output.write(s2);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//closing various scanners
input.close();
stringToRemove.close();
}
}
But for some reason, instead of replacing the string with whitespace, the entire text file becomes empty. What am I doing wrong?
Edit: Okay, so I took everyone's advice and managed to fix the variable problem by introducing a third String variable and using more descriptive variable names.
Scanner s1 = new Scanner(System.in);
String stringToRemove = s1.nextLine();
String fileContents = null;
try {
//stuff here
while (inputFile.hasNextLine()) {
fileContents += inputFile.nextLine();
} catch { //more stuff }
String outputContent = fileContents.replaceAll(stringToRemove, "");
My issue now is that the beginning of the new file starts with "null" before relaying the new content.
String s2 = s1.replaceAll(s1, "");
the first parameter of replaceAll method is what you are looking for to replace, and you are looking for s1, you are saying with this code clean all s1 content...
Where you went wrong is that you appended the file content to s1 which is the string you want to remove.
Try introduce s3 and then do
s2 = s3.replaceAll(s1, "");

Searching content of a file

I dont have alot of experience working with files. I have a file. I have written the following to the file
Test 112
help 456
news 456
Friendly 554
fileOUT.write("Test 112\r\n");//this is a example of how I entered the data.
Now I am trying to search in the file for the word news and display all the content that is in that line that contains the word news.
This is what I have attempted.
if(fileIN.next().contains("news")){
System.out.println("kkk");
}
This does not work. The folowing does find a word news because it displays KKK but I dont have an Idea how to display only the line that it news was found in.
while(fileIN.hasNext()){
if(fileIN.next().contains("Play")){
System.out.println("kkk");
}
}
What must be displayed is news 456.
Thank You
You want to call fileIN.nextLine().contains("news")
Try using the Scanner class if you are not already. It does a wonderful job of splitting input from a stream by some delineator (in this case the new line character.)
Here's a simple code example:
String pathToFile = "data.txt";
String textToSearchFor = "news";
Scanner scanner = new Scanner(pathToFile);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.contains(textToSearchFor)){
System.out.println(line);
}
}
scanner.close();
And here's an advanced code example that does much more than you asked. Enjoy!
//Search file for an array of strings. Ignores case if caseSensitive is false.
public void searchFile(String file, boolean caseSensitive, String...textToSearchFor){
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String originalLine = scanner.nextLine();
String line = originalLine;
if(!caseSensitive) line = line.toLowerCase();
for(String searchText : textToSearchFor){
if(!caseSensitive) searchText = searchText.toLowerCase();
if(line.contains(searchText)){
System.out.println(originalLine);
break;
}
}
}
scanner.close();
}
//usage
searchFile("data.txt",true,"news","Test","bob");
searchFile("data.txt",true,new String[]{"test","News"});
you can try this code...:D
String s = null;
File file = new File(path);
BufferedReader in;
try {
in = new BufferedReader(new FileReader(file));
while (in.ready()) {
s = in.readLine();
if(s.contains("news")){
//print something
}
}
in.close();
} catch (Exception e) {
}

How to keep formatting while reading files

I'm trying to read a .java file into a JTextArea and no matter what method I use to read in the file the formatting is never preserved. The actual code is ok but the comments always get messed up. Here are my attempts.
//Scanner:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
Scanner fileScanner = null;
try
{
fileScanner = new Scanner(file);
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();
//output is a JTextArea
output.append(line + newline);
}
}
catch(FileNotFoundException fnfe)
{
System.err.println(fnfe.getMessage());
}
}
//Scanner reading the full text at once:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
Scanner fileScanner = null;
try
{
fileScanner = new Scanner(file);
fileScanner.useDelimiter("\\Z");
String fullText = fileScanner.next();
//print to text area
output.append(fullText + newline);
}
catch(FileNotFoundException fnfe)
{
System.err.println(fnfe.getMessage());
}
}
//BufferedReader:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
//Scanner fileScanner = null;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line = "";
while((line = reader.readLine()) != null)
{
output.append(line + newline);
}
}
Is there anyway to keep the formatting the same??
PS - Also posted at http://www.coderanch.com/t/539685/java/java/keep-formatting-while-reading-files#2448353
Hunter
Use the JTextArea.read(...) method.
It may be due the var newline being hardcoded as '\n' or something like that. Try defining newline as follows:
String newline=System.getProperty("line.separator");
This solution is more "general", but I would use camickr solution if working with a JTextArea

Categories