public static List getStringList(String fileName) throws IOException{
BufferedReader br = null;
List list = new ArrayList();
String str;
try{
br = new BufferedReader(new FileReader(fileName));
while( (str = br.readLine()) != null ){
list.add(str);
}
}finally{
if(br != null) br.close();
}
return list;
}
Получить все строки файла в виде List<String> (чтение в UTF-8)
public static List getFileLines(String fileName) throws IOException {
List list = new ArrayList();
BufferedReader br = null;
try{
br = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileName),"UTF-8"));
String str;
while( (str = br.readLine()) != null ){
list.add(str);
}
}finally {
if(br != null)
br.close();
}
return list;
}
Получение байтов файла по URL
public static byte[] downloadFile(URL url) throws IOException {
byte[] bytes = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream();
int ch;
while( (ch = is.read()) != - 1){
baos.write((byte)ch);
}
baos.flush();
bytes = baos.toByteArray();
return bytes;
} finally {
baos.close();
if(is != null)is.close();
}
}
Запись переданных строк в файл в кодировке UTF-8
public static void writeToFile(String fileName,List lines)
throws IOException{
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(fileName),"UTF-8"));
for(String str : lines){
bw.append(str).append("\n");
}
bw.close();
}
Запись String, StringBuilder, StringBuffer в файл (UTF-8)
public static void writeToFile(String fileName,CharSequence charSequence)
throws IOException{
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(fileName),"UTF-8"));
bw.append(charSequence);
bw.close();
}