java操作本地text文件

//按字节读取

public static void readByBytes(String url) {
  File file = new File(url);
  InputStream in = null;
  try {
    in = new FileInputStream(file);
    int temp;
    while ((temp = in.read()) != -1) {
      System.out.println(temp);
    }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
}

  

//按字符读取

public static void readByChar(String url){
  File file = new File(url);
  Reader read = null;
  StringBuffer buff = new StringBuffer();
  char[] arr = new char[1024];
  int cha=0 ;
  try {
    read =new InputStreamReader(new FileInputStream(file),"utf-8");
    while((cha=read.read(arr))!=-1){
      buff.append(new String(arr,0,cha));
    }
    System.out.println(buff.toString());
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
}

  

//按行读取

public static void readByLine(String url){
  File file = new File(url);
  try {
    InputStreamReader in = new InputStreamReader(new FileInputStream(file),"UTF-8");
    BufferedReader buff = new BufferedReader(in);
    String text =null;
    while((text = buff.readLine())!=null){
      System.out.println(text);
    }
    } catch (FileNotFoundException e) {
  } catch (UnsupportedEncodingException e) {
  } catch (IOException e) {
  }
}

  

//按行读取

public static void readByLineScan(String url){
  try {
    Scanner in = new Scanner(new File(url));
    while(in.hasNextLine()){
      String str = in.nextLine();
      System.out.println(str);
    }
    } catch (FileNotFoundException e) {
    }
}

  

//通过swing控件读取文件

private static void chooseFile() {
  JFileChooser jfc = new JFileChooser();// 初始化文件选择器
  FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT","txt");// 设置文件过滤,TXT为提示用户选择文件类型,txt为文件过滤后缀
  jfc.setFileFilter(filter);// 将文件过滤加载到选择器中
  int returnVal = jfc.showOpenDialog(null);
  if (returnVal == JFileChooser.APPROVE_OPTION) {
  // 获得打开的文件
  File file = jfc.getSelectedFile();
  File out = new File(file.getParent() + "\\jiagkun.txt");
  try {
    InputStreamReader in = new InputStreamReader(
    new FileInputStream(file), "UTF-8");
    BufferedReader buff = new BufferedReader(in);
    BufferedWriter write = new BufferedWriter(new FileWriter(out));
    String text = null;
    while ((text = buff.readLine()) != null) {
      write.write(text + "\n");
    }
    buff.close();
    write.close();
  } catch (FileNotFoundException e1) {
  } catch (UnsupportedEncodingException e1) {
  } catch (IOException e1) {
  }
  }
}

//字符串写入文件


public static void log(String conent) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\test2.txt", true)));
			out.write(conent + "\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
 

  

posted @ 2016-04-12 18:37  蓝色土耳其  阅读(598)  评论(0编辑  收藏  举报