java text文档_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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值