Output not getting as intened [duplicate] - java

This question already has answers here:
File Write - PrintStream append
(2 answers)
Closed 6 years ago.
I'm trying to read the file "ab.txt" and saving its content in "Output.txt" Kth times,so i'm suppose to get the content of input file K times in output file,but i'm getting only once whereas it is printing on console Kth times.
import java.io.*;
import java.util.Scanner;
class PrintStreamTest1
{
public static void main(String... l)throws IOException
{
int k=0;
long avgTime=0;
while(k<100)
{
long startTime=System.nanoTime();
String s;
Scanner fin=new Scanner(new BufferedInputStream(new FileInputStream("ab.txt")));
PrintStream output=new PrintStream("Output.txt");
while(fin.hasNextLine())
{
s=fin.nextLine();
System.out.println(s);
output.print(s+"\n");
}
avgTime=avgTime+((System.nanoTime()-startTime)/10000000);
fin.close();
output.close();
k++;
}
System.out.println("\n "+ avgTime+"ms");
}
}

You are using the wrong constructor as you can see in the Javadoc :
PrintStream(String fileName)
...
fileName The name of the file to use as the destination of this print stream. If the file exists, then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
You should open the file associated with the PrintStream in append mode if you don't want the content of that file overwritten in each iteration of your loop :
PrintStream output = new PrintStream(new FileOutputStream("Output.txt",true));
Alternately, just open the file once before the loop and close it once after the loop.

Related

Java Scanner doesn't read

I am trying to download a file that contains an integer from a remote machine, increase the value of the integer locally, write the new value to the same file and upload the file. I use scp. It downloads the file successfully. I use shell file for downloading and uploading processes. But I have problems with Scanner.
Here is the code:
import java.io.*;
import java.util.*;
public class shell {
public static void main(String[] args) throws IOException{
Runtime.getRuntime().exec("/home/ayyuce/Desktop/download.sh");
File f= new File("/home/ayyuce/Desktop/yeni.txt");
PrintWriter pw = new PrintWriter(f);
Scanner s= new Scanner(f);
int num=0;
if(s.hasNextLine()){
num=s.nextInt();
} else {
System.out.println("Error");
}
int increase=num++;
pw.println(increase);
Runtime.getRuntime().exec("/home/ayyuce/Desktop/upload.sh");
s.close();
pw.close();
}
}
The output is: Error
I wonder what is the problem with Scanner.
Thank you so much!
PrintWriter pw = new PrintWriter(f);
From javadoc
file - The file to use as the destination of this writer. If the
file exists then it will be truncated to zero size; otherwise, a new
file will be created. The output will be written to the file and is
buffered.
Of course, Scanner can't read anything, because the file was truncated to zero size in new PrintWriter(f).

Java: How to print every output of the console either in the console and in a file?

Evening, I have this need:
Every output of the console should be printed into a file but also still in the console. and the /n should be changed with lineSeparator().
How can I achieve that?
You can assign a PrintStream to System.out with System.setOut().
Thus you have to implement a PrintStream that outputs its input to the old System.out and a file simultaneously. (Overriding the FilterOutputStream.write() method.)
You can print the output in output file by using FileOutputStream and PrintStream, You can try below code for better understanding.
import java.io.*;
public class ReadFile {
public static void main(String[] args) throws FileNotFoundException {
java.io.File outFile = new java.io.File ("File name" );
FileOutputStream fos = new FileOutputStream(outFile);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
for(int i = 0 ; i < 5 ; i++) {
System.out.println(i);
}
}
}
This code prints the output in the text file, If the text file does not exist then it creates a new file and then prints output in the file.

How to write ArrayList<Double> into a file in Java [duplicate]

This question already has answers here:
How to write an ArrayList of Strings into a text file?
(8 answers)
Closed 6 years ago.
I want to write the ArrayList<Double> array into the file in such a way that when I double click on the file then the file opens and the user can read the data.
I have tried the DataOutputStream & RandomAccessFile; both works fine but when I double click on the file it shows data which is not in readable form.
I tried this:
ArrayList<Double> larr=new ArrayList<Double>();
larr.add(5.66);
larr.add(7.89);
try{
FileOutputStream fos = new FileOutputStream("out.txt");
DataOutputStream dos = new DataOutputStream(fos);
for(Double d:larr)
dos.writeDouble(d);
dos.close();
} catch(Exception ex) {
ex.printStackTrace();
}
But now the case is that when I open the file out.txt by double clicking on it. It comes in non-readable form.
I would use a PrintWriter to get human readable values to out.txt (and I would specify the parent folder, personally; I like the user's home directory). Also, I would prefer a try-with-resources close and a method. Something like,
public static void writeList(List<Double> al) {
File f = new File(System.getProperty("user.home"), "out.txt");
try (PrintWriter pw = new PrintWriter(f)) {
for (Double d : al) {
pw.println(d);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Also, you could declare and initialize larr1 in one line like
List<Double> larr = new ArrayList<>(Arrays.asList(5.66, 7.89));
1And please program to the List interface.
It's because the I/O streams you said you tried to use (DataOutputStream and RandomAccessFile) are treating the numbers as binary data, rather than text. You should use a PrintStream.
Example:
PrintStream ps = new PrintStream(new File(filePath));
ps.println(5.25);
ps.close(); // Be sure to close the stream when you're done with saving the numbers
Noticed something familiar with ps.println(5.25)? System.out.println(5.25) does exactly the same thing to the console.

How to prevent overwriting output when writing to a file? [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
Sorry for the confusing title. I tried to make it as concise as possible. I am reading from an input file, parsing it, and writing to an output file. The problem I am having is once the program finishes running, the output file only contains the last item that is read from the input. Each input is being overwritten by the next. I think my problem lies in this code segment.
protected void processLine(String aLine) throws IOException {
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter(" ");
if (scanner.hasNext()){
String input = scanner.next();
PrintWriter writer = new PrintWriter(new FileWriter("output.txt"));
writer.println(input);
writer.close();
} else {
System.out.println("Empty or invalid line. Unable to process.");
}
}
Any and all help/advice is appreciated.
Just add true as a parameter to open the file in append mode
PrintWriter writer = new PrintWriter(new FileWriter("output.txt",true));
Append mode makes sure that while adding new content, the older content is retained. Refer the Javadoc
You could open the file in append mode, but it would be better not to open and close the output file every time around the loop. Open it once before you start, and close it when finished. This will be far more efficient.

How to remove first line of a text file in java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Replace first line of a text file in Java
Java - Find a line in a file and remove
I am trying to find a way to remove the first line of text in a text file using java. Would like to use a scanner to do it...is there a good way to do it without the need of a tmp file?
Thanks.
If your file is huge, you can use the following method that is performing the remove, in place, without using a temp file or loading all the content into memory.
public static void removeFirstLine(String fileName) throws IOException {
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
//Initial write position
long writePosition = raf.getFilePointer();
raf.readLine();
// Shift the next lines upwards.
long readPosition = raf.getFilePointer();
byte[] buff = new byte[1024];
int n;
while (-1 != (n = raf.read(buff))) {
raf.seek(writePosition);
raf.write(buff, 0, n);
readPosition += n;
writePosition += n;
raf.seek(readPosition);
}
raf.setLength(writePosition);
raf.close();
}
Note that if your program is terminated while in the middle of the above loop you can end up with duplicated lines or corrupted file.
Scanner fileScanner = new Scanner(myFile);
fileScanner.nextLine();
This will return the first line of text from the file and discard it because you don't store it anywhere.
To overwrite your existing file:
FileWriter fileStream = new FileWriter("my/path/for/file.txt");
BufferedWriter out = new BufferedWriter(fileStream);
while(fileScanner.hasNextLine()) {
String next = fileScanner.nextLine();
if(next.equals("\n"))
out.newLine();
else
out.write(next);
out.newLine();
}
out.close();
Note that you will have to be catching and handling some IOExceptions this way. Also, the if()... else()... statement is necessary in the while() loop to keep any line breaks present in your text file.
Without temp file you must keep everything in main memory. The rest is straight forward: loop over the lines (ignoring the first) and store them in a collection. Then write the lines back to disk:
File path = new File("/path/to/file.txt");
Scanner scanner = new Scanner(path);
ArrayList<String> coll = new ArrayList<String>();
scanner.nextLine();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
coll.add(line);
}
scanner.close();
FileWriter writer = new FileWriter(path);
for (String line : coll) {
writer.write(line);
}
writer.close();
If file is not too big, you can read is into a byte array, find first new line symbol and write the rest of array into the file starting from position zero. Or you may use memory mapped file to do so.

Categories