[英]Reading multiple text file in Java
我的文本文件很少。 每个文本文件包含一些路径和/或其他文件的引用。
文件1
#file#>D:/FilePath/File2.txt
Mod1>/home/admin1/mod1
Mod2>/home/admin1/mod2
文件2
Mod3>/home/admin1/mod3
Mod4>/home/admin1/mod4
我想要的是,通过仅提供File1.txt
作为我的Java程序的输入,将所有路径Mod1, Mod2, Mod3, Mod4
复制到另一个文本文件中。
到现在为止我做了什么?
public void readTextFile(String fileName){
try {
br = new BufferedReader(new FileReader(new File(fileName)));
String line = br.readLine();
while(line!=null){
if(line.startsWith("#file#>")){
String string[] = line.split(">");
readTextFile(string[1]);
}
else if(line.contains(">")){
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
line=br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
当前,我的代码仅读取File2.txt
的内容,控件不会返回File1.txt
。 请询问是否需要更多输入。
似乎很简单。 假设您当前的代码有效(没有看到任何奇怪的内容),则在填充svnLinks
Map
,您需要编写文件。
因此,在填充Map
,您可以使用以下方法:
File newFile = new File("myPath/myNewFile.txt");
// TODO check file can be written
// TODO check file exists or create
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream(newFile);
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
for (String key: svnLinks.keySet()) {
bw.write(key.concat(" my separator ").concat(svnLinks.get(key)).concat("myNewLine"));
}
}
catch (Throwable t) {
// TODO handle more gracefully
t.printStackTrace();
if (bw != null) {
try {
bw.close();
}
catch (Throwable t) {
t.printStackTrace();
}
}
首先,您在不关闭当前阅读器的情况下跳至另一个文件,而当您回来时,光标会丢失。 首先读取一个文件,然后将其匹配的所有内容写入另一个文件。 关闭当前的读取器(不要关闭写入器),然后打开下一个要读取的文件,依此类推。
这是您方法的非递归实现:
public static void readTextFile(String fileName) throws IOException {
LinkedList<String> list = new LinkedList<String>();
list.add(fileName);
while (!list.isEmpty()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(list.pop())));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("#file#>")) {
String string[] = line.split(">");
list.add(string[1]);
} else if (line.contains(">")) {
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
}
}
只是使用LinkedList来维持顺序。 如果将文件读取限制为一定数量(深度),建议您添加一些计数器。 例如:
while (!list.isEmpty() && readCount < 10 )
这将消除将代码运行到无穷大的机会(在循环引用的情况下)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.