i trying to save this string with a file list into a file but it only saves the last one.. what is the problem here? :(
public void fileprinter() throws IOException{
File dir = new File("c:");
String[] children = dir.list();
if (children == null) {
} else {
for (int i=0; i<children.length; i++) {
String filename = new StringBuffer().append(children[i]).toString();
System.out.println(filename);
Writer output;
File file = new File("D:/file.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(filename);
output.close();
}
}
}
You keep overwriting the same file in the loop, so only the last line will "survive".
Open the BufferedWriter outside of the loop (once!) and close it when done.
An alternative would be to open in append mode, but even then don't reopen the same file in a loop over and over again.
Related
Alright so to get straight to the point I've coded a simple application in which it gets the string of the first line of the files it goes through and then I make it to log all the strings it gets to a txt file but when it logs it just continues to replace itself with the new strings in the other files.
I want it to log the strings it gets then write the new string from the other file in a new line but I cannot seem to make it work.
To anyone who can help me fix this I'd really appreciate it.
public static void main(String[] args) throws Exception {
File dir = new File("C://Users//Test//Desktop//lists");
if (dir.isDirectory()) {
for (File file : dir.listFiles()) {
String line1 = Files.readAllLines(Paths.get(file.getAbsolutePath())).get(0);
BufferedWriter writer = new BufferedWriter(new FileWriter("C://Users//Test//Desktop//logged.txt"));
writer.write(line1);
writer.newLine();
writer.close();
}
}
}
Note :
you must open and close the writer object, outside of for loop
Try this
public static void main(String[] args) throws Exception {
File dir = new File("C://Users//Test//Desktop//lists");
if (dir.isDirectory()) {
BufferedWriter writer = new BufferedWriter(new FileWriter("C://Users//Test//Desktop//logged.txt"));
for (File file : dir.listFiles()) {
String line1 = Files.readAllLines(Paths.get(file.getAbsolutePath())).get(0);
writer.write(line1);
writer.newLine();
}
writer.close();
}
}
You are reopening the file logged.txt in each iteration of your text loop. This will truncate the file and start writing at the beginning again. If you really want to reopen the file, you need to use append mode: FileWriter("filename.txt", true), but you probably want to open the BufferedWriter before your loop and close it afterwards.
You new your writer every time. Add the new line before the for begins.
public static void main(String[] args) throws Exception {
File dir = new File("C://Users//Test//Desktop//lists");
if (dir.isDirectory()) {
BufferedWriter writer = new BufferedWriter(new FileWriter("C://Users//Test//Desktop//logged.txt"));
for (File file : dir.listFiles()) {
String line1 = Files.readAllLines(Paths.get(file.getAbsolutePath())).get(0);
writer.write(line1);
writer.newLine();
}
writer.close();
}
}
I used this code in a different application to write a name and highscore onto the file for my game. Now i'm using this code to get a name and password from a .DAT file and be able to add a new user and password. Here's the .DAT file.
michael123
speaker123
katherine123
motor123
username
password
Here's the code. Reading the file works fine but writing to it does nothing at all and i'm unsure why.
InputStream file;
BufferedReader fileStream;
FileWriter fileWriter;
BufferedWriter fileWrite;
String temp = "";
int users = 0;
public void readUserInfo() throws IOException {
try {
file = Board.class.getResourceAsStream("users.DAT");
fileStream = new BufferedReader(new InputStreamReader(file));
} catch (Exception e) {
System.out.println("File not found");
}
for (int i = 0; i < users; i++) {
temp = fileStream.readLine();
Board.username[i] = temp.trim();
temp = fileStream.readLine();
Board.password[i] = temp.trim();
}
//Close
fileStream.close();
file.close();
}
public void addUser() throws IOException {
fileWriter = new FileWriter(Board.class.getResource("users.DAT").getFile(),true);
fileWrite = new BufferedWriter(fileWriter);
System.out.println("Users : " + users);
//Skip already created users
for (int i = 0; i < users; i++) {
fileWrite.newLine();
fileWrite.append(Board.username[i]);
fileWrite.newLine();
fileWrite.append(Board.password[i]);
}
System.out.println("Adding" + Board.username[users] + " : " + Board.password[users]);
//Add user
fileWrite.newLine();
fileWrite.append(Board.username[users]);
fileWrite.newLine();
fileWrite.append(Board.password[users]);
//Close
fileWrite.close();
System.out.println("Closed fileWrite");
}
I'm using netbeans. The file being read from is in the same package as all the other classes.
Maybe you have packaged your jar with some state of the file users.DAT (a defined set of users) and when you read them from classpath you see only the users from the time you have created the jar. The writing goes then to another file.
You should read the user from the filesystem too.
Check the working directory of your app there should be correct file containing the users added.
Also no need for copying all the user over and over again every time you add one, just open your file in append mode
fileWriter = new FileWriter(new File("users.DAT"), true);
Unless you want to be able to delete users, in that case keep everything in memory and save when you exit the program or explicitly with a save action.
In your reading you use file = Board.class.getResourceAsStream("users.DAT"); in your writing you just create a file new File("users.DAT") what about changing your addUser() to
public void addUser() throws IOException {
fileWriter = new FileWriter(Board.class.getResource("users.DAT").getFile());
....
}
Edit: The problem is that during writing you are not retrieving the same file as before. I would add this method
public File getUserDataFile() {
return new File(Board.class.getResource("").getFile(), "users.DATA");
}
// then use it like this
new FileWriter(getUserDataFile());
// and
new BufferedReader(new InputStreamReader(getUserDataFile()));
then access it whenever you want to read and write to your file. The problem is Board.class.getResourceAsStream("users.DAT") will return null if your file doesnt exist.
I am saving to a file a double list (mydata) which is some data the user enters and a string list (dates_Strings) which is the current date.
The user enters some data and pressing a 'save' button , I save the data and the currents date.
So , user may enter "1" and press save (1, 08/05/13)
enter "2" and press save (2, 08/05/13).
Because the user may enter data during a day (same date) I don't want to save many instances of the date.I want to save all the user data in that date.
I tried sth like:
for (int i=1;i<mydata.size();i++){
bw.write(mydata.get(i)+",");
while (!(dates_Strings.get(i).equals(dates_Strings.get(i-1))))
bw.write(dates_Strings.get(i)+"\n");
}
but it saves only the last entered data.
I am saving as:
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();
File file = new File(directory, filename);
FileOutputStream fos;
//saving them
try {
fos = new FileOutputStream(file,true); //true in order to append
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i=1;i<mydata.size();i++){
//if (!(dates_Strings.get(i).equals(dates_Strings.get(i-1))))
bw.write(mydata.get(i)+","+dates_Strings.get(i)+"\n");
}
value.setText("");
bw.flush();
bw.close();
} catch (IOException e2) {
e2.printStackTrace();
}//catch
}
I am loading as:
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
File file = new File(directory, filename);
String s;
FileInputStream fis;
try {
fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
do {
s = br.readLine();
if (s != null ){
String[] splitLine = s.split(",");
mydata.add(Double.parseDouble(splitLine[0]));
//dates_Strings.add(thedate.parse(splitLine[1]));
dates_Strings.add(splitLine[1]);
}
} while (s != null );
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Mmmm... maybe this can help you, basic idea as mentioned by our colleagues: receive input, save it in file, receive new input, read the existing file before, add the new content to the old content and save the updated content of your file.
//Asumming your values are these:
List<String> datesList = new ArrayList<String>();
List<Double> dataList = new ArrayList<Double>();
//You must fill your data of course...
//I use a buffer to put in order my data
StringBuffer stringAppender = new StringBuffer();
for (int i = 0; i < dataList.size(); i++) {
stringAppender.append(dataList.get(i));
stringAppender.append(",");
stringAppender.append(datesList.get(i));
if (i != dataList.size()-1) {
stringAppender.append("\n");
}
}
//I use the Buffered Writer and then save all the data ordered in one single String.
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/home/mtataje/saved.txt")));
bw.write(stringAppender.toString());
bw.close();
Then... you have new inputs right?
//I read my file first
BufferedReader br = new BufferedReader(new FileReader(new File("/home/mtataje/saved.txt")));
String line;
StringBuffer auxBuffer = new StringBuffer();
while ((line = br.readLine()) != null) {
auxBuffer.append(line);
auxBuffer.append("\n");
}
//Then append to the StringBuffer again, but your StringBuffer has data saved inside :)
for (int i = 0; i < newDataListIncoming.size(); i++) {
auxBuffer.append(newDataListIncoming.get(i));
auxBuffer.append(",");
auxBuffer.append(newDatesIncoming.get(i));
if (i != newDataListIncoming.size()-1) {
auxBuffer.append("\n");
}
}
//And write your file
BufferedWriter bw2 = new BufferedWriter(new FileWriter(new File("/home/mtataje/saved.txt")));
bw2.write(auxBuffer.toString());
bw2.close();
Of course, you will use methods and not use redundancy in your code as me, I hope I gave you a hand with this. Best regards.
You must load the previous value in your file .. read it and add new value .. then save it !
How to list all folders in a directory without changing order even when new files are added, in a file using Java? When I run the program it is going to an infinite loop with "Not checked" comment which I put in order to look whether it is checking the file.
try
{
BufferedWriter bufferedWriter = null;
bufferedWriter = new BufferedWriter(new FileWriter("d://my.txt"));
BufferedReader br = new BufferedReader(new FileReader("d://my.txt"));
int i=1;
File f=new File("D:/Moviezzz");
File[] fi=f.listFiles();
for(File fil:fi)
{
if(!fil.isHidden() && (fil.isDirectory() || fil.isFile()))
{
int s=i++;
String files = fil.getName();
String thisLine;
while(null != (thisLine="\t"+br.readLine()))
{
String exist[]=thisLine.split("\t");
//ensure that it is already written in file
if(exist[0].equals(files))
{
System.out.println("Checked");
}
//ensure that it is not written in file
else
{
System.out.println("Not Checked");
}
}
bufferedWriter.write(s+"\t"+files);
bufferedWriter.newLine();
bufferedWriter.flush();
System.out.print("yes");
// bufferedWriter.write(s+" "+files);
}
br.close();
//Construct the BufferedWriter object
System.out.println("Succ");
}
}
catch(Exception ex)
{
System.out.println("failed");
}
You're getting an infinite loop, because the condition in your while loop can never be false.
while(null != (thisLine="\t"+br.readLine()))
you're essentially adding "\t" to the results of readLine(), so the value you're comparing to null will never actually be null. It will always have a \t in it.
After further research, it appears like thisLine will be be "\tnull" once you've reached the end of the stream
If I were you, I wouldn't do all that in your while loop. I'd do something more like this.
while(null != (thisLine=br.readLine()))
{
thisLine = "\t"+ + thisLine;
...
This is driving me crazy! I have a panel that displays a list of files from a directory. The list is stored in a vector. When I click on a button, a new file is created in the same directory and the list needs to be refreshed.
I don't understand why Java cannot see the new file, even though if I add a good old DIR in Dos, Dos can see the file. It's as if the new file is invisible even though I can see it and Dos can see it. I tried giving it some time (sleep, yield) but it's no use. I also tried copying to a new temp file and reading the temp but again to no avail. Here's some code (removed some irrelevant lines):
public class Button extends EncapsulatedButton {
public Button()
{
super("button pressed");
}
public void actionPerformed(ActionEvent arg0) {
//removed function here where the new file is created in the directory
//remove call to DOS that regenerates /myFileList.txt after a new file was added in the directory
//at this point, DOS can see the new file and myFileList.txt is updated, however it is read by java without the update!!!!!
//now trying to read the directory after the new file was created
Vector data = new Vector<String>();
String s = null;
// Create the readers to read the file.
try {
File f = new File("/myFileList.txt");
BufferedReader stream = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
while((s = stream.readLine()) != null)
{
data.addElement(s.trim());
}
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
util();
}
void util(){
//giving it time is not helping
Thread.yield();
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
//get the file listing through java instead of DOS - still invisible
File fLocation = new File("/myDir");
File[] filesFound = fLocation.listFiles();
for (int i = 0; i < filesFound.length; i++) {
if (filesFound[i].isFile()) {
System.out.println("**********" + filesFound[i].getName());
}
}
//last resort: copy to a temp then read from there - still not good
try{
//copy to a temp file
File inputFile = new File("/myFileList.txt");
File outputFile = new File("/myFileList_temp.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
//read the copy to see if it is updated
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("/myFileList_temp.txt");
// Get the object of DataInputStream
DataInputStream in1 = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in1));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println ("Test file read: " + strLine);
}
//Close the input stream
in1.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
I would appreciate any leads. Thank you.
myFileList.txt lokks like this:
myline1
myline2
myline3
After adding a new file in the folder,
myline4 should appear in it, then it will be read and displayed in the panel.
Honestly, your code is a mess.
You read from /myFileList.txt and do nothing with what you read, except store it in a temporary Vector. At best, this has no effect; at worst (if the file doesn't exist, for example) it throws an exception. Whatever it does, it does not create a new file.
Furthermore, I see no reference to the panel in your GUI that supposedly displays the file list. How do you expect it to get updated?
This works for me:
To refresh the directory list, call .listFiles() again.
filesFound = fLocation.listFiles();
should show the most updated directory listing. Hope this helps you.