Description
write text, make every line starts with prefix
Parameter
Parameter | Description |
---|
bw | a parameter |
text | a parameter |
prefix | a parameter |
Exception
Parameter | Description |
---|
IOException | an exception |
Declaration
public static void writeText(BufferedWriter bw, String text,
String prefix) throws IOException
Method Source Code
//package com.java2s;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void writeText(File file, String text) throws IOException {
writeText(file, text, null);//www . j ava 2s . c om
}
public static void writeText(File file, String text, String charsetName)
throws IOException {
byte[] bytes = charsetName == null ? text.getBytes() : text
.getBytes(charsetName);
writeBytes(file, false, bytes);
}
/**
* write text, make every line starts with prefix
* @param bw
* @param text
* @param prefix
* @throws IOException
* @see Properties
*/
public static void writeText(BufferedWriter bw, String text,
String prefix) throws IOException {
int len = text.length();
int current = 0;
int last = 0;
while (current < len) {
char c = text.charAt(current);
if (c == '\n' || c == '\r') {
if (last != current)
bw.write(prefix + text.substring(last, current));
bw.newLine();
last = current + 1;
}
current++;
}
if (last != current)
bw.write(prefix + text.substring(last, current));
bw.flush();
}
/**
* write bytes into file
* @param file
* @param append
* @param bytes
* @throws IOException
*/
public static void writeBytes(File file, boolean append, byte[] bytes)
throws IOException {
if (bytes.length == 0)
return;
FileOutputStream output = new FileOutputStream(file, append);
output.write(bytes);
output.flush();
output.close();
}
}