Can not write all the data to txt file - java

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?

Related

How to append a line in a file or before encountering newline character?

Input File:
Online_system_id
bank_details
payee
credit_limit
loan_amount
Online_system_id
bank_details
payee
credit_limit
loan_amount
Expected Output:
Online_syatem_id
bank_details
payee
credit_limit
loan_amount
proc_online_system_id
Online_syatem_id
bank_details
payee
credit_limit
loan_amount
proc_online_system_id
Below is the code given for reference.
I want to add a line after each record i.e before encountering the blank line.
What changes do I need to do?
String line;
int flag=0;
PrintStream out = new PrintStream(outputFile);
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
if(!line.contains("proc_online_system_id")){
flag=1;
}
}
if(flag==1)
out.print("proc_online_system_id");
String line;
PrintStream out = null;
BufferedReader br = null;
try {
out = new PrintStream(new FileOutputStream(outputFile));
br = new BufferedReader(new FileReader(inputFile));
while((line=br.readLine())!=null){
if(line.trim().isEmpty()) {
out.println("proc_online_system_id"); //print what you want here, BEFORE printing the current line
}
out.println(line); //always print the current line
}
} catch (IOException e) {
System.err.println(e);
} finally {
try{
out.close();
br.close();
} catch (Exception ex) {
System.err.println(ex);
}
}
And don't forget the out.close(); and br.close(); afterwards.
This solution stores only the current line in memory, as opposed to Dakkaron's answer, which is correct, but needs to store the whole file in memory (in a StringBuilder instance), before writing to file.
EDIT: After Vixen's comment, here is the link, in case you have java 7, and you want to use try with resources in your solution.
Try this code
String line;
PrintStream out = new PrintStream(outputFile);
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
if (!line.trim().isEmpty()){
line+="\n";
}
//System.out.println(line);
}
Buffer each block. So what you do is read the file line by line and store the content of the current block in a StringBuilder. When you encounter the empty line, append your additional data. When you did that with the whole file, write the content of the StringBuilder to the file.
String line;
int flag=0;
PrintStream out = new PrintStream(outputFile);
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
if(!line.contains("proc_online_system_id")){
flag=1;
}
if (line.isEmpty() && flag==1) {
flag=0;
builder.append("proc_online_system_id\n");
}
builder.append(line).append("\n");
}
out.print(builder.toString());

Not entering while loop

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());

Redirect file I/O of sub process java

I am opening a new file and trying to write to it inside a sub process in java. I used the process builder to start the sub process. The file is being created but whatever content I want to write to the file is not getting written. Is there a way to solve this? I can redirect stdin, stdout and stderr of sub process but how to redirect the file I/O. I want to do it on java version 1.7
process is started:
ArrayList<String> params = new ArrayList<String>();
for (int i = 0; i < cmdarray.length; i++) {
params.add(cmdarray[i]);
}
try {
//java.lang.Process process = Runtime.getRuntime().exec(cmdarray);
ProcessBuilder builder = new ProcessBuilder(params);
final java.lang.Process process = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
file is created inside the sub process:
BufferedWriter br;
try {
br = new BufferedWriter(new FileWriter(new File("text.txt")));
br.write("This should be present in the file.");
}
catch (IOException e) {
e.printStackTrace();
}
You forget to close the BufferedWriter br, this is why the String is not getting written in the file.
Try this, may help :
BufferedWriter br;
try {
br = new BufferedWriter(new FileWriter(new File("text.txt")));
br.write("This should be present in the file.");
br.close();
} catch (IOException e) {
e.printStackTrace();
}

Importing a text file in Android SDK

I've been trying to read a file for the last few days and have tried following other answers but have not succeeded. This is the code I currently have to import the text file:
public ArrayList<String> crteDict() {
try {
BufferedReader br = new BufferedReader
(new FileReader("/program/res/raw/levels.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] linewrds = line.split(" ");
words.add(linewrds[0].toLowerCase());
// process the line.
}
br.close();
}
catch (FileNotFoundException fe){
fe.printStackTrace();
It is meant to read the text file and just create a long Array of words. It keeps ending up in the FileNotFoundException.
Please let me know any answers.
Thanks!
IF your file is stored in the res/raw folder of the android project, you can read it as follows, this code must be inside an Activity class, as this.getResources() refers to Context.getResources():
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.levels);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}

Reading a variable number of lines from a file

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

Categories

Resources