1 1 /** 2 2 * 3 3 * @Description: 写文件 4 4 * @param @param url 要写到服务器的路径 5 5 * @param @param fileName 要写的文件名 需要加前缀 如 .txt 6 6 * @param @param bodydata 要写的内容 7 7 * @param @return 成功返回1 失败返回0 8 8 * @return String 9 9 */ 1010 public static String writeFile (String url,String fileName,byte[] bodydata){ 1111 StringBuffer sb = new StringBuffer(); 1212 String message = ""; 1313 try{ 1414 sb.append(url).append(fileName); 1515 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(sb.toString(), true)), "UTF-8")); 1616 bw.write(new String(bodydata,"UTF-8")); 1717 message = "1"; 1818 bw.flush(); 1919 bw.close(); 2020 System.out.println("运行完毕!!!"); 2121 }catch(Exception e){ 2222 message = "0"; 2323 e.printStackTrace(); 2424 } 2525 return message; 2626 } 2727 2828 /** 2929 * 3030 * @Description: 读文件 3131 * @param @param filename 文件路径名加文件名 3232 * @param @return 3333 * @return byte[] 3434 */ 3535 public static byte[] readFileByte(String filename){ 3636 BufferedInputStream in = null; 3737 ByteArrayOutputStream bos = null; 3838 try{ 3939 File file = new File(filename); 4040 if(file.isFile() && file.exists()){ //判断文件是否存在 4141 bos = new ByteArrayOutputStream((int)file.length()); 4242 in = new BufferedInputStream(new FileInputStream(file)); 4343 int buf_size = 1024; 4444 byte[] buffer = new byte[buf_size]; 4545 int len = 0; 4646 while(-1 != (len = in.read(buffer,0,buf_size))){ 4747 bos.write(buffer,0,len); 4848 } 4949 }else{ 5050 System.out.println("找不到指定的文件"); 5151 } 5252 in.close(); 5353 bos.close(); 5454 }catch(Exception e){ 5555 e.printStackTrace(); 5656 } 5757 return bos.toByteArray(); 5858 } 5959 6060 /** 6161 * 6262 * @Description: 读文件 6363 * @param @param filepath 要读的文件的路径加文件名称 6464 * @param @param encoding 编码格式 6565 * @param @return 成功返回 1 失败返回 0 6666 * @return String 6767 */ 6868 public static String readFileLine(String filepath,String encoding) { 6969 String message = ""; 7070 try { 7171 File file=new File(filepath); 7272 if(file.isFile() && file.exists()){ //判断文件是否存在 7373 InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);//考虑到编码格式 7474 BufferedReader bufferedReader = new BufferedReader(read); 7575 String lineTxt = null; 7676 while((lineTxt = bufferedReader.readLine()) != null){ 7777 System.out.println(lineTxt); 7878 } 7979 read.close(); 8080 }else{ 8181 System.out.println("找不到指定的文件"); 8282 } 8383 }catch (Exception e) { 8484 System.out.println("读取文件内容出错"); 8585 e.printStackTrace(); 8686 } 8787 return message; 8888 }
JAVA读写文件
Wesley13
2021-10-11
1305 0 0
点赞
收藏
评论区
加载中...