I would like to know how to write all lines from the java output in a .txt file.
I've done some tests so far but I don't seem to be able to find the solution :/
Here is a small code, if you could show me with this one, it would be greatly appreciated :
The code shown below asks the user what to write in a .txt file but I want it to write all the printed lines in a .txt file without asking the user anything. Thank you
package test;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Test {
public static void main(String[] args)throws Exception {
System.out.println("Hello");
System.out.println("Hi");
System.out.println("Hola");
System.out.println("Bonjour");
System.out.println("Hallo");
System.out.println("Hej");
System.out.println("Alo");
System.out.println("Ciao");
writeOutput();
}
public static void writeOutput() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String lineFromInput = in.readLine();
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
out.println(lineFromInput);
out.close();
}
}
Use directly PrintStream to write the String values.
public static void main(String[] args)throws Exception {
PrintStream printStream = new PrintStream(new File("output.txt"));
// hook for closing the stream
Runtime.getRuntime().addShutdownHook(new Thread(printStream::close));
// writing
write(printStream,"Hello", "Hi", "Hola", "Bonjour", "Hallo", "Hej",
"Alo","Ciao");
// writing again
write(printStream, "A new String", "And again another one...");
}
public static void write(PrintStream printStream, String... values) throws Exception {
try{
for (String value : values){
printStream.println(value);
}
printStream.flush();
}
catch (Exception e){
// handling exception
}
}
}
java test.Test > somefile.txt
Related
I am trying to write strings to a file but all the strings are being written to the file once the script is terminated.
To make my problem clear, in the below code I want to write a single string to my files per second and my file should be updated each second. Please help I am new to java.
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException {
String[] list = "Should write each word in each iteration".split("\\s");
for(String word:list){
Writer obj = new Writer();
obj.func(word);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
}
class Writer{
public void func(String word) throws IOException{
FileWriter writer = new FileWriter("file" , true);
writer.write(word);
writer.close();
}
}
I made this homework exercise to read text from a text file and store it reversed into another new file. This is the code:
import java.util.*;
import java.io.*;
public class FileEcho {
File file;
Scanner scanner;
String filename = "words.txt";
File file1 ;
PrintWriter pw ;
void echo() {
try {
String line;
file = new File( filename);
scanner = new Scanner( file );
file1 = new File("brabuhr.txt");
pw = new PrintWriter(file1);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
scanner.close();
} catch(FileNotFoundException e) {
System.out.println( "Could not find or open file <"+filename+">\n"+e
);
}
}
public static void main(String[] args) {
new FileEcho().echo();
}
}
and here is a picture Picture here
The question is: why is the newly generated file decreased in size despite having the same characters but reversed?
Would be great if someone can explain it because even my professor didn't know why is that.
P.S; the context of the file is just some words from the dictionary.
Also in other students computers so the problem is not from my computer
The problem is that you never closed the output stream pw, so that any pending output isn't written to the underlying file. This may cause truncation of your file.
You should have closed the output stream with pw.close() in a finally, or in a try with resources.
try (pw = new PrintWriter(file1)) {
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
}
Your implementation can be simplified to be the following:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileEcho {
void echo() throws IOException {
try (PrintWriter pw = new PrintWriter("brabuhr.txt")) {
Files.lines(Paths.get("words.txt"))
.map(s -> new StringBuilder(s).reverse().toString())
.forEach(pw::println);
}
}
public static void main(String[] args) throws IOException {
new FileEcho().echo();
}
}
In this example I used a 'try-with-resources' to have the PrintWriter pw autoclosed.
I have the following short python program "test.py"
n = int(raw_input())
print n
I'm executing the above program from following java program "ProcessRunner.java"
import java.util.*;
import java.io.*;
public class ProcessRunner {
public static void main(String[] args) {
try {
Scanner s = new Scanner(Runtime.getRuntime().exec("python test.py").getInputStream()).useDelimiter("\\A");
System.out.println(s.next());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Upon running the command,
java ProcessRunner
I'm not able to pass a value 'n' in proper format to Python program and also the java run hangs. What is the proper way to handle the situation and pass a value to 'n' dynamically to python program from inside java program?
raw_input(), or input() in Python 3, will block waiting for new line terminated input on standard input, however, the Java program is not sending it anything.
Try writing to the Python subprocess using the stream returned by getOutputStream(). Here's an example:
import java.util.*;
import java.io.*;
public class ProcessRunner {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("python test.py");
Scanner s = new Scanner(p.getInputStream());
PrintWriter toChild = new PrintWriter(p.getOutputStream());
toChild.println("1234"); // write to child's stdin
toChild.close(); // or you can use toChild.flush()
System.out.println(s.next());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
An alternative is to pass n as a command line argument. This requires modification of the Python script to expect and process the command line arguments, and to the Java code to send the argument:
import java.util.*;
import java.io.*;
public class ProcessRunner {
public static void main(String[] args) {
try {
int n = 1234;
Process p = Runtime.getRuntime().exec("python test.py " + n);
Scanner s = new Scanner(p.getInputStream());
System.out.println(s.next());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
And the Python script, test.py:
import sys
if len(sys.argv) > 1:
print int(sys.argv[1])
If I understand you correctly you want your java program to pass any output from your python script to System.out and any input into your java program to your python Script, right?
Have a look at the following program to get an idea how you could do this.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ProcessRunner {
public static void main(String[] args) {
try {
final Process process = Runtime.getRuntime().exec("/bin/sh");
try (
final InputStream inputStream = process.getInputStream();
final InputStream errorStream = process.getErrorStream();
final OutputStream outputStream = process.getOutputStream()
) {
while (process.isAlive()) {
forwardOneByte(inputStream, System.out);
forwardOneByte(errorStream, System.err);
forwardOneByte(System.in, outputStream);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void forwardOneByte(final InputStream inputStream,
final OutputStream outputStream)
throws IOException {
if(inputStream.available() <= 0) {
return;
}
final int b = inputStream.read();
if(b != -1) {
outputStream.write(b);
outputStream.flush();
}
}
}
Note This code is just a concept demo. It will eat up your cpu and will not be able to cope with bigger amounts of throughput.
I have a .csv file that I want to load in Java so that afterwards I will be able to work on it as on a normal matrix (array). Here you can see my code:
package MirMir;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Try1 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner scanner = new Scanner(new File("/Users/Madalin/NetBeansProjects/imp fr/src/com/mkyong/util/Tracker.csv"));
scanner.useDelimiter(",");
while (scanner.hasNext())
{
System.out.print(scanner.next() + "|");
}
scanner.close();
}
}
The program runs perfectly without any errors, just the output I get in the end is: "BUILD SUCCESSFUL (total time: 0 seconds)" and that's all, without any data or anything.
Here is another way for this
public class Tracker {
public static void main(String[] args) throws FileNotFoundException, IOException
{
File f =new File("D:/Tracker.csv");
BufferedReader br = new BufferedReader(new FileReader(f));
String s ;
while ((s=br.readLine())!=null)
{
System.out.println(s);
}
br.close();
}
}
Well this might work ;)
P.S. Change the file location
The code is fine. No problem. I tested it on a sample csv file.
There seems to be some problem with your csv file.
Post a sample from your csv.
I am just trying to reverse the lines which I receive from the input, but every single time I run my code, the output.txt file is empty. What am I missing?
It appears mostly correct to me, even the recursion passage.
Thanks
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class ReverseLines {
public static BufferedReader input;
public static PrintWriter output;
public static void main(String[] args) throws Exception{
input = new BufferedReader(new FileReader(args[0]));
output = new PrintWriter(new FileWriter(args[1]));
reverse(input, output);
}
public static void reverse( BufferedReader input, PrintWriter output)
throws Exception {
String line = input.readLine();
if(line != null) {
reverse (input, output);
output.println(line);
}
}
}
Close the PrintWriter in your main method:
output.close();
do output.flush() and check whether it works!