-
Saving to text file
Hello everyone! I have been messing around with this code I have been trying to get to work correctly all night. Basically I was just wanted it to read all the files in one folder, and save the titles to a text file. I have gotten everything else working, but when I attempt to save it to a text file it only saves the very last file name. Can someone please help me out before I drive myself crazy. Here is my code :
Code:
import java.io.*;
import java.util.*;
public class DirectoryReader {
private static int arraySize;
public static void main(String[] args) {
File folder = new File("E:/Videos/Movies");
File[] listOfFiles = folder.listFiles();
String[] orderedTitles = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String fileName = (listOfFiles[i].getName());
int cd1Index = fileName.indexOf("CD1");
int cd2Index = fileName.indexOf("CD2");
int cd3Index = fileName.indexOf("CD3");
int cd4Index = fileName.indexOf("CD4");
int endIndex = fileName.indexOf(".");
String newName;
if (cd1Index > 0) {
newName = fileName.substring(0,cd1Index-2);
} else if (cd2Index > 0) {
newName = fileName.substring(0,cd2Index-2);
} else if (cd3Index > 0) {
newName = fileName.substring(0,cd3Index-2);
} else if (cd4Index > 0) {
newName = fileName.substring(0,cd4Index-2);
} else {
newName = fileName.substring(0,endIndex);
}
orderedTitles[i] = newName;
} else {
System.out.println("There is an incorrect file present in folder.");
}
arraySize = i;
}
SortedSet set = new TreeSet();
for (int k = 0; k < orderedTitles.length; k++) {
set.add(orderedTitles[k]);
}
Iterator it = set.iterator();
while (it.hasNext()) {
// Get element
Object element = it.next();
saveFile(element);
System.out.println(element);
}
}
public static void saveFile(Object title) {
FileOutputStream fout;
try {
// Open an output stream
fout = new FileOutputStream ("myMovies.txt");
// Print a line of text
new PrintStream(fout).println (title);
// Close our output stream
fout.close();
}
// Catches any error conditions
catch (IOException e) {
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
}
Thank you very much!
-
every time you open the file, you overwrite it. open it once, write into it, and close it once.
-
You put append true.
fout = new FileOutputStream ("myMovies.txt",true);
-
That would make a lot of sense, I did not even think of that. Thanks iluxa. I tried just adding true like you said RamyaSivakanth, and it seems to be working fine now. Thanks a lot, you both were a lot of help.