我目前创建了一个Java应用程序,可以从ini文件中读取键值。该键值使用绝对路径指向一个目录(例如c:\temp)。我试图使用键值的String变量将其转换为File变量,然后在FileReader中使用该变量。我遇到的问题是,手表服务会启动,但当我用str.txt文件修改手表目录时,它会抛出错误,并且没有通过switch case语句运行。我也试过在bufferedReader中使用Path变量,这就是为什么你会在try语句中看到它也没有工作,我想我应该知道的。
下面是结果。
java.io.FileNotFoundException: z: \java_apps (Access is denied)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import org.ini4j.Wini;
public class readIni {
public static String iniPath;
public static Path directory;
public static BufferedReader br;
public static void main(String[] args) throws IOException {
try {
Wini ini = new Wini(new File("z:\\java_apps\\java.ini"));
iniPath = ini.get("filepath", "filepath");
WatchService watchService = FileSystems.getDefault().newWatchService();
directory = Paths.get(iniPath);
WatchKey watchKey = directory.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
while(true) {
for (WatchEvent<?> event : watchKey.pollEvents()) {
try {
//read text into buffReader from file
Path path = directory.resolve((Path)event.context());
File file = new File(iniPath);
br = new BufferedReader(new FileReader(file));
System.out.println(file);
//create empty string, read file content line by line while the line is not empty
String str = "";
String line = br.readLine();
while (line != null) {
str= line;
line = br.readLine();
//begin switch
当程序第二次试图打开并读取该文件时,是否该文件仍然被程序打开?
这就可以解释 access denied
消息。
在这种情况下,我建议在读取结束时关闭文件。
我通过在ini文件中创建另一个指向文本文件的条目来解决这个问题。我创建了另一个字符串来指向文本文件,而不是使用iniPath变量,该变量必须由Paths.get()来使用。最初,我使用inipath作为文本文件的字符串,这让我产生了错误。
try {
//outter try
//read ini file create, instantiate variables
Wini ini = new Wini(new File("z:\\java_apps\\java.ini"));
iniPath = ini.get("filepath", "filepath");
textFile = ini.get("file", "file");
Then later in the code
try {
//inner try
//read text into buffReader from file
Path path = directory.resolve((Path)event.context());
File file = new File(textFile);