我是Java新手,一直在尝试实现一个创建目录及其相应文件的函数。其中一个文件是"mapping.txt“,它位于名为NodeA的文件夹中。mapping.txt的内容是NodeA的绝对路径。
请找到下面的代码,我已经尝试过了。为了更好地理解,我已经在所有可能的地方进行了评论。我想知道我不能在文件中写入的原因。任何帮助都将深表感谢。
//-------------------------- To create Node and their respective Files ------------------------------------------------------
for(int j=0;j<alpha.length;j++){ //alpha is a String array which contains {"A","B","C","D"}
node_directory=Node.concat(alpha[j]); // nodde_directory is "C:\Users\Desktop\Node. I concat A,B,C and D to create different directories.
File dir = new File(node_directory);
if(!dir.exists()){
dir.mkdirs();
}
System.out.println("Path: \n" +dir.getAbsolutePath());
System.out.println();
List<String> fileList = Arrays.asList(files); // files is an array of string containing "mapping" and "data".
Iterator <String> iter = fileList.iterator(); //I traverse through the list.
while(iter.hasNext()){
File next_file = new File(node_directory+"\\"+iter.next()+".txt"); //while traversing, I append the current "iter.next" to "node_directory" and append ".txt" to create files.
System.out.println("The Files are: \n" +next_file);
System.out.println();
// I created the Directories, mapping and data Files for each directory.
/*I am stuck here, as it is not writing the path in the mapping File */
if(iter.next()=="mapping"){ // I check if iter.next is mapping, so that i can write in the mapping file, the path of Folder containing mapping file.
BufferedWriter br = new BufferedWriter(new FileWriter(next_file));
br.write(next_file.getAbsolutePath());
}
if(!next_file.exists()){
System.out.println(next_file.createNewFile());
}
我意识到发生了什么。因为我正在遍历列表中的字符串数组。问题出现在这里:
next_file = new File(node_directory+"\\"+iter.next()+".txt"); // This line creates files by appending the required data. Since iter.next() returns all the Files in one go,
BufferedWriter br = new BufferedWriter(new FileWriter(next_file));
br.write(dir.getAbsolutePath());
next_file一次创建了所有文件。我需要知道如何在创建后检查每个文件,以便我可以编辑该文件。
谢谢。
发布于 2013-06-13 13:22:25
if(iter.next().equals("mapping")
发布于 2013-06-13 13:27:07
首先,将iter.next()
赋给一个局部变量:
String fileName= iter.next();
因为下次调用它时,迭代器会跳转到下一个值,您可能会得到NoSuchElementException
,并且肯定会得到错误的结果。然后,在其余代码中使用此fileName
变量。
另一个错误是将字符串与==
进行比较。String是一个不可变的对象,通过使用==
,您只是比较对象引用,而不是对象。因此,当与==
进行比较时,两个完全相同的字符串可能会产生false。而是使用.equalsTo()
:
if (fileName.equals("mapping"))
https://stackoverflow.com/questions/17088044
复制相似问题