加入收藏 | 设为首页 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > 本地

java 获取本地文件夹路径怎么写

时间:2024-03-07 07:51:57  来源:http://www.gzrxw.net  作者:admin

一、java 获取本地文件夹路径怎么写

构造File对象,使用File对象取上级目录,再取绝对路径 File f = new File(c:\\temp\\01\\1.txt); if(f.exists()){ System.out.println(f.getParentFile().getAbsolutePath()); }

二、Java 读取txt文件

我采用模糊匹配的方法在文件中查找输入的关键字,你可以看一下:

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class Search {

//测试

public static void main(String[] args) {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String str,ans = null;

try {

//读入用户输入的需要查找的信息

str = br.readLine();

if (str != null) {

//如果输入非空,则到文件中去寻找

ans = search(str);

}else{

//如果输入为空,提示用户

System.out.println(你没有输入需要寻找的信息);

}

} catch (IOException e) {

e.printStackTrace();

}

//输出查询结果

if(!ans.equals()){

StringTokenizer st = new StringTokenizer(ans);

//按记录一条一条输出

while(st.hasMoreTokens()){

String number = st.nextToken();

String name = st.nextToken();

String door = st.nextToken();

System.out.println(学号:+number+; 姓名:+name+; 寝室号:+door);

}

}else{

System.out.println(没有可以匹配的信息);

}

}

//在文件中查找用户输入的关键字,并返回找到的记录

private static String search(String str) {

String all = ;

File file = new File(F:/java/StudentApartments.txt);

try {

BufferedReader br = new BufferedReader(new FileReader(file));

String s = br.readLine();

while(s!=null){

if (s == null) {

System.err.println(数据读完了!);

} else {

//判断当前读入的记录行中是否有输入的关键字,如果有保存起来

if(s.indexOf(str)!=-1){

all = all + + s;

}

}

s = br.readLine();

}

br.close();// 一定要关闭资源

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return all;

}

}

三、Java如何读取txt文件的内容

public class Myword {

    public static void main(String[] args) throws IOException {

        try {

            FileInputStream file = new FileInputStream(e:/myText.txt);

            BufferedInputStream Bfile = new BufferedInputStream(file);

            byte[] b = new byte[1024];

            String s = ;

            int bytesRead=0;  

            while((bytesRead=Bfile.read(b))!=-1){

                s+= new String(b,0,bytesRead);

            }

            System.out.println(s); 

            }

     }

来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
相关文章
    无相关信息
栏目更新
栏目热门