java - How to compare String to all elements in an array? -
this question has answer here:
- how can test if array contains value? 24 answers
i looking way compare string (which in case line text file) every element in array , see if there match. @ high level overview, have string array (about 100 elements) full of strings contained somewhere in file need deleted. reading file stringbuffer , writing each line, except skipping on lines match element in array. have far:
//main class calling method public class testapp { public static void main(string[] args) { compareanddelete.removeduplicatelines("c:/somelocation", 2darray); } } public class compareanddelete { static string line_of_text; static stringbuffer localbuff = new stringbuffer(); static filereader buffer; static bufferedreader user_file; public static void removeduplicatelines(string local, string[][] duplicates) throws ioexception { //converting 2d array one-dimensional array final string[] finaldups = new string[duplicates.length]; for(int = 0; < duplicates.length; i++) { finaldups[i] = duplicates[i][0]+" "+duplicates[i][1]; } int count = 0; user_file = new bufferedreader(buffer); set<string> values = new hashset<string>(arrays.aslist(finaldups)); while((line_of_text = user_file.readline()) != null){ if(!(values.contains(line_of_text))){ localbuff.append(line_of_text+"\n"); }else{ count++; } } system.out.println(count); //printing stringbuffer file bufferedwriter testoutfile = new bufferedwriter(new filewriter("c:/test.txt")); testoutfile.write(localbuff.tostring()); testoutfile.flush(); testoutfile.close(); }
so unsure of if statment, know not work properly, removing first few elements in new stringbuffer because lines happen towards end of file, , not recheck every line match each element. know there has better way this... in advance help/suggestions.
**updated: code above, throwing following error on line:
while((line_of_text = user_file.readline()) != null){
error:
exception in thread "main" java.io.ioexception: stream closed @ sun.nio.cs.streamdecoder.ensureopen(streamdecoder.java:51) @ sun.nio.cs.streamdecoder.read(streamdecoder.java:204) @ java.io.inputstreamreader.read(inputstreamreader.java:188) @ java.io.bufferedreader.fill(bufferedreader.java:147) @ java.io.bufferedreader.readline(bufferedreader.java:310) @ java.io.bufferedreader.readline(bufferedreader.java:373) @ compare.compareanddelete.removeduplicatelines(compareanddelete.java:48) @ mainpackage.testapp.main(testapp.java:326)
this can accomplished quite efficiently adding string
array members set
, , checking whether set contains()
current line. example:
set<string> ignoredstrings = new hashset<string>(arrays.aslist(arr)); string line; while ((line = file.readline()) != null) { if (!ignoredstrings.contains(line)) { buffer.append(line); buffer.append("\n"); } }
Comments
Post a Comment