Frage

I'm trying to create a modified version of a file by omitting certain lines from the original file if they do not meet a certain requirement. I'm not sure how to accomplish this. When I read in files, I use

BufferedReader(new FileReader(new File(...)))

I suppose I will use BufferedWriter to write out to file, but I have never used BufferedWriter before. I'm confused about the write() method. What is the difference (besides the obvious one that they take different parameters) between

write(char[] cbuf, int off, int len)

and

write(String s, int off, int len)

When should I use one vs. the other? If I want to write ONLY the lines that meet a certain requirement, will something like this work:

if(/** meets specific condition */) {
   out.write(/**not sure which of the two above to use*/);
}

Or should I use another type of writer, like FileWriter?

War es hilfreich?

Lösung

BufferedWriter also inherits write(String) from Writer, which just takes a string. You can append the newline yourself.

myBufferedWriter.write(str + "\n");

Or:

myBufferedWriter.write(str);
myBufferedWriter.newLine();

Check out the docs for BufferedWriter and at the bottom of the "Method Summary" section you'll see "Methods inherited from...". All javadocs have this format. There you can find a list of the methods it inherits.

Note that FileWriter also has a write(String), which you can use directly. The BufferedWriter provides an extra layer of buffering, which is useful for improving performance in applications that write large amounts of data, but probably won't have much of an effect for your case. BufferedWriter does add newLine(), though, which might float your boat.

Alternatively, you could use a PrintWriter, then you will have println().

As for your question about write(char[], int, int) vs. write(String, int, int) -- both of those are useful when you want to write specific substring from the source instead of writing the whole thing. E.g.:

myBufferedWriter.write("Baseballs are square", 4, 5);

Would write "balls".

The char[] vs. String is just a matter of how you are holding the data you want to write. You can write from a String, or you can write from a char array:

char[] arr = new char[]{'m','a','t','h','e','m','a','t','i','c','a','l','!'}; 
String str = "mathematical!";

myBufferedWriter.write(arr); // char[]
myBufferedWriter.write(new String(arr)); // String
myBufferedWriter.write(str); // String
myBufferedWriter.write(str.toCharArray()); // char[]

Andere Tipps

Suggestions:

1) Use a BufferedReader/FileReader so you can use "readLine()":

BufferedReader in = new BufferedReader(new FileReader(file));    
while (in.ready()) {
  String s = in.readLine();
  ...
}
in.close();

2) Use a regex to evaluate whether or not the line meets your condition

3) Write a line at a time/evaluate/write matching lines

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top