我已经为 makefile 编写了一个 java 应用程序。该应用程序会抓取文件夹中的文件并一一读取它们以获取包含文件。但它不会报告所有文件。该应用程序是:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class testCrawler {
/**
* @param args
*/
static String path = "C:\\APP_Eclipse\\TestCrawler\\Test";
static Scanner sc;
static FileReader fr;
static BufferedReader br;
static FileWriter fw;
static BufferedWriter bw;
static String make = "makefile";
static String line;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File f = new File(path);
folderCrawler(f);
}
static public void folderCrawler(File f) throws IOException{
File[] files = f.listFiles();
String name;
String[] names;
fw = new FileWriter(make);
bw = new BufferedWriter(fw);
for(File aFile:files){
name = aFile.getName().toLowerCase();
names = name.split("\\.");
bw.write(names[0] + ".o : " + name);
if ((name.endsWith(".c") || (name.endsWith(".h")))){
try{
fr = new FileReader(path + "\\" + name);
br = new BufferedReader(new FileReader(path + "\\" + name));
while((line=br.readLine()) != null){
line = line.trim();
if (line.contains("#include") && line.contains("\"")){
line = line.replace("#include", "");
line = line.replace("\"", "");
line = line.trim();
System.out.println("LINE : " + line);
bw.write(" " + line + " ");
makeMakefile(line);
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
bw.write("\n");
}
}
br.close();
bw.close();
}
static public void makeMakefile(String name) throws Exception{
br = new BufferedReader(new FileReader(path + "\\" + name));
while((line=br.readLine()) != null){
if (line.contains("#include") && line.contains("\"")){
line = line.replace("#include", "");
line = line.replace("\"", "");
line = line.trim();
System.out.println("LINE : " + line);
bw.write(" " + line + " ");
makeMakefile(line);
}
}
}
}
读取的文件: test.c 包含:
#include "test.h"
#include "test_1.h"
Test.h 包含:
#include "test_2.h"
#include "test_3.h"
以及文件 test_1.h、test_2.h 和 test_3.h(这些文件不包含任何内容)。
生成文件应该是:
test.o : test.c test.h test_1.h
test.o : test.h test_2.h test_3.h
test_1.o : test_1.h
test_2.o : test_2.h
test_3.o : test_3.h
但是:
test.o : test.c test.h
test.o : test.h test_2.h
test_1.o : test_1.h
test_2.o : test_2.h
test_3.o : test_3.h
我知道错误来自哪里:从 makeMakefile 返回时 line=br.readLine() 变为 null,并且我无法读取文件中的网络行。
如何避免这种情况?
非常感谢
EB
最佳答案
当您调用 makeMakeFile()
时,您将重新定义您的 BufferedReader
,并且您将传递从 C 文件读取的行,而不是文件名。因此,当您只有一个 #include
时,它总是有效,但此后就不起作用了,因为 br
现在指向一个与 C 代码中的行对应的文件,该文件可能不存在,但您抛出一个 FileNotFoundException
并在 main 中处理它。
此外,为什么要在 main 中调用代码,然后立即在另一个函数中调用代码?
关于java - 读取链接文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20174977/