Ignore the arguments being passed into the method.
My code:
public static void setEnabled(EntityPlayer p, Boolean b){
try{
FileReader fileReader = new FileReader(SLInfo.STORAGEFILE);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(SLInfo.STORAGEFILE);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line = null;
boolean breakearly = false;
bufferedWriter.write("HeLlo");
bufferedWriter.newLine();
bufferedWriter.write("World!");
System.out.println("GOT TO THIS FRICKIN POINT");
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
Thread.sleep(2000);
}
bufferedReader.close();
bufferedWriter.close();
}catch(Exception e){e.printStackTrace();}
}
This is simply outputting "GOT TO THIS FRICKIN POINT" (I decided this string in my fury). I have no idea why. In my file, it shows:
"Hello"
"World"
I just don't get it.
EDIT: Cool. I didn't know that. Unfortunately, that was just a simple example that I thought would solve my problem... it didn't. Taking a look at my code below, and assuming that the file contains p.username, which is a string, on line 1, why is "got here" never printed and "did this" always printed. What I expected it to do: If p.username is on line x, it changes line x to read "p.username booleanvalue" and if p.username is not anywhere in the file, "p.username booleanvalue" is appended to the last line in the file.
public static void setEnabled(EntityPlayer p, Boolean b){
try{
FileReader fileReader = new FileReader(SLInfo.STORAGEFILE);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(SLInfo.STORAGEFILE);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line = null;
boolean breakearly = false;
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
if (line.contains(p.username)){
System.out.println("Got here");
bufferedWriter.write(p.username + " " + Boolean.toString(b));
bufferedWriter.newLine();
bufferedWriter.flush();
breakearly = true;
break;
}
}
bufferedWriter.flush();
System.out.println(breakearly);
if (!breakearly){
System.out.println("did this");
bufferedWriter.write(p.username + " " + Boolean.toString(b));
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedReader.close();
bufferedWriter.close();
}catch(Exception e){e.printStackTrace();}
}
(Yes, I know I have excessive flushes)
This is where the Buffered in BufferedWriter comes in.
You write two lines, which due to buffering are stored in memory.
You then read from the file, which has nothing written to it yet.
Then you close the writer, causing the buffers to flush, adding the contents to the file.
To force flushing before you read, you can use bufferedWriter.flush(), or close it.
You are not flushing your output:
Try this code
boolean breakearly = false;
bufferedWriter.write("HeLlo");
bufferedWriter.newLine();
bufferedWriter.write("World!");
// flush
bufferedWriter.flush();
// close the bufferwriter
bufferedWriter.close();
now read your file again
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
Thread.sleep(2000);
}
When you write to file, you acctualy write to file cache, try calling bufferedWriter.close() to save all changes.
write these lines:
bufferedWriter.flush(); // flush
// now close the bufferwriter
bufferedWriter.close();
now read your file again
while((line = bufferedReader.readLine()) != null){
// your reading code
}
Related
I'm trying to write in a file whatever the user has written.
The file creates and all but the program fails to write whatever the user wrote from the program, to the file (The program is like notepad). It wont enter the while loop because the String line is null even if I write something in my program.
It seems it's returning null when I print the "line" String after using br.readLine().
while ((line = br.readLine()) != null) {
bw.write(line);
textArea.append("it worked");
}
Full code:
try {
path = fileChooser.getSelectedFile().getAbsolutePath().replace('\\', '/')
+ "/";
File file = new File(path + File.separator +
JOptionPane.showInputDialog(null, "File name", "File") + ".txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
textArea.append("it worked");
}
bw.flush();
bw.close();
textArea.append(path);
} catch(IOException e1) {
e1.printStackTrace();
}
file.createNewFile();
. . .
BufferedReader br = new BufferedReader(new FileReader(file));
The reader works from an empty file that just has been created. Of course br.readLine() will return null immediately since the file is empty.
Instead of the while loop, I would simply write:
bw.write(textArea.getText());
I have a problem with writing data to my .txt file. It doesn't write all the data to my .txt file. I have tried it to put everything in a array, but also that doesn't works.
My code:
BufferedWriter writer = null;
try {
String line;
Process p = Runtime.getRuntime().exec("ps -A -o pid");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
writer = new BufferedWriter(new FileWriter(" the path .."));
writer.write(line);
System.out.println(line);
}
writer.close();
input.close();
} catch (Exception err) {
err.printStackTrace();
System.out.println("Sorry!");
}
It writes only the last line of the console.
By re-creating the object without closing it during every iteration of the loop, you are discarding what you have written so far (You have to use writer.close() to save what you have written using the object).
You will need to declare writer before the loop, so change it to the following
BufferedWriter writer = null;
try {
String line;
Process p = Runtime.getRuntime().exec("ps -A -o pid");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
writer = new BufferedWriter(new FileWriter(" the path .."));
while ((line = input.readLine()) != null) {
writer.write(line);
System.out.println(line);
}
writer.close();
input.close();
} catch (Exception err) {
err.printStackTrace();
System.out.println("Sorry!");
}
Can I just ask, why were you re-declaring the writer object every iteration?
I am trying to append to a text file but for some reason it keeps overwriting it, here's my code:
File logFile = new File(Environment.getExternalStorageDirectory().toString(), "notifications.txt");
try {
if(!logFile.exists()) {
logFile.createNewFile();
}
StringBuilder text = new StringBuilder(); // build the string
String line;
BufferedReader br = new BufferedReader(new FileReader(logFile)); //Buffered reader used to read the file
while ((line = br.readLine()) != null) { // if not empty continue
text.append(line);
text.append('\n');
}
BufferedWriter output = new BufferedWriter(new FileWriter(logFile));
output.write(text + "\n");
output.close();
alertDialog.show();
} catch (IOException ex) {
System.out.println(ex);
}
thank you in advance
use
new FileWriter(logFile, true)
Where the second parameter tells it to append, not overwrite.
Found in this question. In the related questions on the right.
Documentation can be found here
You need to use the other constructor of FileWriter that specifies whether the data is overwritten or appended. Use FileWriter(logFile, true) instead of what you have now :)
I am trying to read a variable number of lines from a file, hopefully using InputStream object. What I'm trying to do (in a very general sense) is as follows:
Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
write to file
I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful.
You can have something like this
BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
while (br.readLine() != null && linesWritten < maxLines) {
//Your logic goes here
}
Have a look at these:
Buffered Reader and
Buffered Writer
//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
while ((line = br.readLine()) != null) {
allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
}
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader
//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer
public static void main(String[] args) {
ArrayList<String> studentTokens = new ArrayList<String>();
ArrayList<String> studentIds = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File("file1.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0) && (!strLine.contains("#"))) {
String[] students = strLine.split("\\s+");
studentTokens.add(students[TOKEN_COLUMN]);
studentIds.add(students[STUDENT_ID_COLUMN]);
}
}
for (int i=0; i<studentIds.size();i++) {
File file = new File("query.txt"); // The path of the textfile that will be converted to csv for upload
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replace("sanid", studentIds.get(i)).replace("salabel",studentTokens.get(i)); // Here the name "sanket" will be replaced by the current time stamp
FileWriter writer = new FileWriter("final.txt",true);
writer.write(newtext);
writer.close();
}
fstream.close();
br.close();
System.out.println("Done!!");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
The above code of mine reads data from a text file and query is a file that has a query in which 2 places "sanid" and "salabel" are replaced by the content of string array and writes another file final . But when i run the code the the final does not have the queries. but while debugging it shows that all the values are replaced properly.
but while debugging it shows that all the values are replaced properly
If the values are found to be replaced when you debugged the code, but they are missing in the file, I would suggest that you flush the output stream. You are closing the FileWriter without calling flush(). The close() method delegates its call to the underlying StreamEncoder which does not flush the stream either.
public void close() throws IOException {
se.close();
}
Try this
writer.flush();
writer.close();
That should do it.