WindowsJNDI对文件用BufferedReader进行读取

时间:2021-03-15 22:41:56
package com.zking.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class TestWindowsJNDI {
public static void main(String[] args) {
try {
//实例化一个Hashtable的集合,参数都放String类型
Hashtable<String, String> environment = new Hashtable<String, String>();;
//windows中有一个工厂 初始化上下文工厂 值是规定的
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
//获取某个文件夹下所有的文件和文件夹
Context context=new InitialContext(environment);
//lookup中放你要读的文件路径,用转义符
 File file=(File)context.lookup("d:\\桌面文件\\桌面\\新建文本文档.txt");
BufferedReader br=new BufferedReader(new FileReader(file));
String str=null;
while((str=br.readLine())!=null){
System.out.println(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}



键值对的值需要从jar包中获取到,下面有步骤

点击进这一步,把com.sun.jndi.fscontext.FSContext  copy到值里面

从项目中的Referenced Librarie——>fscontext.jar——>com.sun.jndi.fscontext——>FSContext.class


environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");


WindowsJNDI对文件用BufferedReader进行读取


需要导的Jar包

fscontext.jar与providerutil.jar