string - How can i remove a word/line and replace it with a new one in a txt file (Java)? -
for example have .txt file:
name smth
year 2012
copies 1
and want replace that:
name smth
year 2012
copies 0
using java.io.*.
here code that. let me know if have question.
import java.io.bufferedreader; import java.io.bufferedwriter; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstreamreader; import java.io.outputstreamwriter; import java.io.writer; import java.util.linkedhashmap; import java.util.map; public class test2 { map<string, string> somedatastructure = new linkedhashmap<string, string>(); file filedir = new file("c:\\temp\\test.txt"); public static void main(string[] args) { test2 test = new test2(); try { test.readfileintoadatastructure(); test.writefilefromadatastructure(); } catch (ioexception e) { system.out.println(e.getmessage()); } } private void readfileintoadatastructure() throws ioexception { bufferedreader in = new bufferedreader(new inputstreamreader( new fileinputstream(filedir))); string line; while ((line = in.readline()) != null) { if (line != null && !line.trim().isempty()) { string[] keyvalue = line.split(" "); // own index , null checks here sample somedatastructure.put(keyvalue[0], keyvalue[1]); } } in.close(); } private void writefilefromadatastructure() throws ioexception { writer out = new bufferedwriter(new outputstreamwriter( new fileoutputstream(filedir))); (string key : somedatastructure.keyset()) { // apply whatever business logic want apply here mybusinessmethod(key); out.write(key + " " + somedatastructure.get(key) + "\n"); out.append("\r\n"); out.append("\r\n"); } out.flush(); out.close(); } private string mybusinessmethod(string data) { if (data.equalsignorecase("copies")) { somedatastructure.put(data, "0"); } return data; } }
Comments
Post a Comment