How do I process (using Java) input from one .txt file, then send it to another .txt file? I have heard of piping, but after hours of searching on the internet, I still couldn't find how to do it.
Asked
Active
Viewed 65 times
1 Answers
0
public static void main (String[] args) throws FileNotFoundException
{
Scanner sc = new Scanner(new File(args[0]));
double sum=0;
String token="0";
try
{
PrintWriter writer = new PrintWriter((args[1]), "UTF-8");
while(sc.hasNextLine())
{
String line=sc.nextLine();
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext())
{
token=lineScan.next();
sum+=Double.parseDouble(token);
}
//System.out.println(sum);
writer.println(sum);
sum=0;
lineScan.close();
}sc.close();
writer.close();
}
catch (IOException e) {
System.out.print("error");
}
}
}
this is an example of a file input and output. The first commandline argument being the file which you want to read from the the second commandline argument being the .txt file you want to write to (or you could replace "args[x]" with blah1.txt). This file reads from a text file containing numbers on each line and adds them up and prints them out to the output file.
So, if your input txt file was:
1 5 10
2
4 3
then your output file would be
16
2
7
I hope this helps.

kirkpatt
- 625
- 5
- 21

MichaelWag
- 1
- 3