3.
static String loadStream(InputStream in) throws IOException {
int ptr = 0;
in = new BufferedInputStream(in);
StringBuffer buffer = new StringBuffer();
while( (ptr = in.read()) != -1 ) {
buffer.append((char)ptr);
}
return buffer.toString();
}
4.
import java.io.*; public class ByteArrayTest{ pubblic static void main(String[] args){ String tmp = "abcdefghijklmnopqrst"; byte[] src = tmp.getBytes(); ByteArrayInputStream input = new ByteArrayInputStream(src); ByteArrayOutputStream output = new ByteArrayOutputStream(); tranform(input,output); byte[] result = output.toByteArray(); //返回一个字节数组 System.out.println(new String(result)); //把字节数组中的所有数据转换成字符串 } //transform函数的作用是用于将输入流当中的数据读取出来,然后将它进行转换。 publci static void transform(InputStream in, OutputStream out){ int ch = 0; try{ while((ch = in.read()) != -1){ //判断读取是否结果 int upperCh = Character.toUpperCase((char)ch); out.write(upperCh); } } catch(Exception e){ e.printStackTrace(); } } }
5.
static public String loadFile(String filename) { File file = new File( filename ); try { Reader rdr = new FileReader( file ); long sz = file.length(); //一次全部读入 char[] ch = new char[(int)sz]; rdr.read(ch); rdr.close(); return new String(ch); } catch(IOException ioe) { return null; } }
6.
static public boolean saveFile(String filename, String contents) { try { File file = new File( filename ); if(file.getParent()== null) { new File(file.getParent()).mkdirs(); } Writer wtr = new FileWriter( file ); char[] ch = contents.toCharArray(); wtr.write(ch); wtr.close(); return true; } catch(IOException ioe) { return false; } } try{ ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; InputStream inStream=socket1.getInputStream(); //得到输入流 //如果buff装满没有取走,则阻塞 while ((rc=inStream.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); //每次写入特定的数据到流中 } byte[] in_b = swapStream.toByteArray(); File fp=new File(path); FileOutputStream filein=new FileOutputStream(fp); filein.write(in_b); } catch(Exception e) { }
8.
import java.io.File; public class Search { String path = null; public String searchFile(File dir, String fileName) { if(dir.isFile()) { if(dir.getName().equals(fileName)) path = dir.getAbsolutePath(); } if (dir.isDirectory()) { //dir中所有的文件和目录 File[] files = dir.listFiles(); File f ; for (int i=0;i<files.length;i++ ){ f = files[i]; path = searchFile(f, fileName); } } return path; } public static void main(String[] args) { if (args.length < 2) { System.out.println("请输入参数"); System.exit(0); } File dir = new File(args[0]); String fileName = args[1]; if (!dir.exists()) { System.out.println("目录不存在:" + dir); System.exit(0); } String path = new Search().searchFile(dir,fileName); if(path!=null) System.out.println("文件完整路径:" + path); else System.out.println("不存在此文件"); } }