java字节流
public class HelloWorld {
public static void main(String[] args) {
String path = "d:\\aaa\\test.txt";
outputFile(path, "nimeiadzcxzcdaaaaae");
String result = inputFile(path);
System.out.println("读取结果" + result);
}
/**
* 获取文件内容
* @param saveFilePath 要读取的文件位置
* @return 读取到的字符串
*/
private static String inputFile(String saveFilePath) {
File file = new File(saveFilePath);
if(!file.exists()){
return "文件不存在";
}
FileInputStream fis = null;
StringBuffer sb = null;
try {
fis = new FileInputStream(file);
sb = new StringBuffer();
int len = 0;
byte[] b = new byte[1024];
while (-1 != (len = fis.read(b))) {
String s = new String(b, 0, len);
sb.append(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
/**
* 输出内容到文件
* @param saveFilePath 文件的保存路径
* @param saveStr 要写入的字符串
*/
private static void outputFile(String saveFilePath, String saveStr) {
File file = new File(saveFilePath);
File parentFile = file.getParentFile();
if(!parentFile.exists()){
parentFile.mkdirs();
}
byte[] bytes = saveStr.getBytes();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void delFile(String saveFilePath){
File file = new File(saveFilePath);
file.delete();
}
}