cjs11225
cjs11225

Reputation: 11

Java Modify text file content from Jtextfiields as input

Currently I get stuck in the modification parts. I having a "booklist.txt":

aaa-bbb-ccc-ddd

qqq-www-eee-rrr

    String q=oldID.getText();
    String w=newID.getText();
    String a=Author.getText();
    String r=title.getText();
    String t=quantity.getText();
            try{
    File f= new File("BookList.txt");
    FileReader fr=new FileReader(f);
    BufferedReader br=new BufferedReader(fr);
    FileWriter fw=new FileWriter(f);
    String line=br.readLine();
    String oldtext="";
    String newtext="";
    String[] tem=new String[4];

    while(line!=null)
    {
    oldtext +=line+System.getProperty("line Seperator");
    tem=line.split("-");
    if(tem[0].equals(q)){
            newtext = oldtext.replaceAll(line,w+"-"+e+"-"+r+"-"+t);
            }     
    }
    fw.write(newtext);        
    fw.close();
    br.close();
            }catch(IOException Ex){Ex.printStackTrace();}

What i want is get input from the Jtexfields and replace the strings in the text file.

Example: if the id that I type is qqq(tem[0]) then the while loop will read all the line in text file.If the qqq that i type is found, modify the other strings which is www, eee, and rrr. The input to replace these strings are from the Jtextfields (String q,w,e,r,t)

Upvotes: 0

Views: 57

Answers (1)

Basil Battikhi
Basil Battikhi

Reputation: 2668

in order to write in a file use FileWriter!

here is what should you do

FileWriter writer=new FileWriter(path);
writer.writeln(newText);
writer.flush();
writer.close();

this will create a file even if the file path doesn't exist. Be aware this will remove all content in the file and the content will be replaced. However if you don't want to replace the content add a parameter to FileWriter object to be like this

new FileWriter(path,true);

this will append the current content with the new content you want to add

UPDATE

I'm not sure if that what is you need First thing you have to read the whole file the second step you need to put the whole lines into ArrayList due arrayList is dynamic array

finally do your compare

Scanner scanner=new Scanner(new File(path));
ArrayList<String>list=new ArrayList<String>();
while(scanner.hasNextLine()){list.add(scanner.nextLine())}

finally for example you want to replace something let us assume QQQ as you mention

if(list.contains("QQQ"))
{
list.replace("QQ",myNewText)>0
}else list.add(myNewText);

Upvotes: 0

Related Questions