I am trying to write contents to a file, but once the while loop prints all the lines , it get's stuck and doesn't go to the next line. The line after while loop are not being executed. My first guess was that maybe the fstream is still waiting for another line, but the while loop does check if no more data then it should come out.
Please help me out here !
Thanks.
//Code
File file;
DataInputStream inputData = new DataInputStream(newPeerConnection.getInputStream());
file = new File(
"F:\\Workspace\\PeerToPeer\\src\\ncsu\\csc\\socketClasses\\out\\out.txt");
#SuppressWarnings("resource")
PrintWriter fstream = new PrintWriter(new FileWriter(
file, true));
if (!file.exists()) {
file.createNewFile();
}
System.out.println("Writing to file: ");
while ((strval = inputData.readUTF()) != null) {
System.out.println(strval);
fstream.println(strval);
//fstream.flush();
//fstream.close();
}
//These lines are not executed
System.out.println("Do you want to download another file (Y/N)?");
wantToContinue = scannerObj.next();
out.writeUTF(wantToContinue);
out.flush();}
I guess your while loop is blocked by inputData.readUTF().
You should ensure the input stream of newPeerConnection is closed by another port, otherwise inputData will wait for next input and inputData.readUTF() blocks.
Related
I have data file “ReadFile1.txt”. I want to read each data from ReadFile1.txt and manipulate those data then write the results in another file “WriteFile2.txt”. Here is my function. The problem is it only reads 2nd,4th, and so on and does write only 2nd result. What’s wrong in this code? I appreciate your help.
public void doManipulate() throws NumberFormatException, IOException {
int multiple = 10;
try {
FileInputStream file = new FileInputStream("ReadFile1.txt");
InputStreamReader input = new InputStreamReader(file);
BufferedReader reader = new BufferedReader(input);
String data1;
while ((data1 = reader.readLine()) != null) {
int data2 = 0;
data1 = reader.readLine();
data2 = Integer.parseInt(data1);
int compressedFrames = data2*multiple;
File file2 = new File("WriteFile2.txt");
FileWriter writer = new FileWriter(file2);
writer.write(String.valueOf(compressedFrames) + "\n");
writer.flush();
writer.close();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
You're calling reader.readLine() twice for every iteration of the while loop - the first time is in the loop declaration, which reads every odd line, and the second is just a couple of lines down (data1 = reader.readLine();). The second call is blowing away anything read by the first before you have a chance to parse it. Removing the second call should fix the "every other line" issue.
Another issue is that you're closing the writer at every iteration of the while loop - don't close the writer until the while loop is done or your output file will only have the first parsed data element in it after your program closes.
How can I save multiple lines into One Text File?
I want to print "New Line" in the same Text File every time the code is executed.
try {
FileWriter fw = new FileWriter("Test.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("New Line");
pw.close();
}
catch (IOException e)
{
System.out.println("Error!");
}
I'm able to create a new file but can't create a new line every time the code is executed.
Pass true as a second argument to FileWriter to turn on "append" mode.
FileWriter fw = new FileWriter("filename.txt", true);
That will make your file to open in the append mode, which means, your result will be appended to the end of the file each time you'll write to the file. You can also write '\n' after each content writing so that it will inserts a new line there.
You are creating a new line every time it is run, the problem is that you are truncating the file when you open it. I suggest you append to the file each time.
try (FileWriter fw = new FileWriter("Test.txt", true); // true for append
PrintWriter pw = new PrintWriter(fw)) {
pw.println("New Line");
} // try-with-resource closes everything.
Note: openning and closing a file for each line is expensive, If you do this a lot I suggest leaving the file open and flushing the output each time.
You are doing this:
FileWriter fw = new FileWriter("Test.txt");
which is overwriting the file every time you execute that line...
BUT you need instead to append the data to the file
FileWriter fw = new FileWriter("Test.txt", true);
take a look at the constructor in the doc
You need to open the file in append mode. You can do that as follows:
FileWriter fw = new FileWriter("Test.txt", true);
Here is the documentation for the same.
I know this is very basic stuff but for some reason I'm having problems with a bufferedReader/ Writer. I am trying to get the first line of text and return it to another method. However, for some reason the writer doesn't seem to be writing to the temp file and it isn't changing the name of the temp file either.
By throwing a few print statements I have been able to figure out:
The while loop is operating correctly
The if else statement is operating correctly
The tempFile is not writing to a text file correctly
The tempFile is not renaming correctly
There are no errors being thrown
private static String wavFinder() throws IOException{
String currentWav=null;
int x = 1;
File inputFile = new File("C:\\convoLists/unTranscribed.txt");
File tempFile = new File("C:\\convoLists/unTranscribedtemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine = null;
while((currentLine = reader.readLine()) != null) {
if(x == 1){
currentWav = currentLine;
}
else{
writer.write(currentLine);
}
x = 2;
}
boolean successful = tempFile.renameTo(inputFile);
System.out.println("Success: " + successful);
System.out.println("currentWav = " + currentWav);
return currentWav;
}
Here is the method I am using. If you notice anything please let me know and if you have any questions I will be sure to answer them quickly. Thank you :)
First flush the steam(writer) and close them.
You can not have two files with same name. You are trying to rename the temp file with input file. You need to delete input file and then rename it to that.
reader.close();
writer.flush();
writer.close();
inputFile.delete();
Add these lines before rename and it will work
Close your buffers before trying to call renameTo.
reader.close()
writer.close()
File inputFile = new File("C:\convoLists/unTranscribed.txt");
File tempFile = new File("C:\convoLists/unTranscribedtemp.txt");
Why you have different signs for path?
Always should be //.
private static void displaytoFile(int trial, int count) {
// TODO Auto-generated method stub
String answer;
try{
// Create file
FileWriter fstream = new FileWriter(outputfile);
BufferedWriter out = new BufferedWriter(fstream);
answer = "Case #"+trial+": "+count;
out.write(answer);
out.newLine();
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
The displaytoFile() method is called in a loop in my project but i am not able to write line by line into the file.It only writes the last line ie the parameters passed during the last iteration.I tested in console and the other code is ok,it displays all but this code snippet seems to have some problem as it seems it overwrites the previous values.How can i get to write to file line by line?
Use the FileWriter(String, boolean) constructor in order to append the input instead of rewriting the entire file:
FileWriter fstream = new FileWriter(outputfile, true);
FileWriter fstream = new FileWriter(outputfile);
BufferedWriter out = new BufferedWriter(fstream);
answer = "Case #"+trial+": "+count;
out.write(answer);
out.newLine();
//Close the output stream
out.close();
has problem. This is because inside each iteration of your loop, you clear the file then write current line into it. you should open the file before the loop and close it after the loop. Or making sure that you are append to the file, not first clear then write, like what you did now.
You have to indicate that you want to append to the file
See method documentation here
I am creating one text file which will connected to some server.
this text file will receive its contents from the server.
It will receive the some text data continuously.
To limit the file size , I am checking no.of lines in the file and if exceeds the mark I am clearing file content. Server will write from the beginning.
Below is the code I have used to do this :
LineNumberReader myReader = new LineNumberReader( new FileReader(new File("mnt/sdcard/abc.txt")));
while(true) {
while(myReader.readLine() != null) {
counter ++;
}
if(counter > 100 ) {
PrintWriter writer = new PrintWriter("/mnt/sdcard/abc.txt");
writer.print("");
writer.close();
writer = null;
counter = 0;
}
}
But after I clear the contents in a file my "counter" not increasing.
But my file is having some data.
I think after reading done I have set my "myReader" to some intial..?
If its how to set that to initial so that .readLine() should start from begining.
Shouldn't you close myReader before writing to the file??
LineNumberReader myReader = new LineNumberReader( new FileReader(new File("mnt/sdcard/abc.txt")));
while(true)
{
while(myReader.readLine() != null) {
counter++;
}
if(counter > 100 )
{
//CLOSE myReader
myReader.close();
PrintWriter writer = new PrintWriter("/mnt/sdcard/abc.txt");
writer.print("");
writer.close();
writer = null;
counter = 0;
//REOPEN myReader
myReader = new LineNumberReader( new FileReader(new File("mnt/sdcard/abc.txt")));
}
}
Shouldn't you make sure that changes to the file done by the server and changes to the file done by this loop are synchronized??
can you show how and where counter is declared and what other code might be modifying it? it is a matter of guessing without seeing that. meanwhile, maybe you can consider not reading the file content all the time and use the file size to determine if you should clean it.
long limit= .... //add your limit in bytes
long fileSize = new File("mnt/sdcard/abc.txt").length();
if (fileSize > limit){
//clean the file
}
please also note to check what was mentioned in the other answers regarding closing the file or trying to clean it while it is open and the server is writing to it.
Issue a myReader.reset() after clearing the contents.