如何将输出写入控制台和文件?
How to write the output to console and file?
我必须输出方法 sayHello() 两次。
输出应该写入控制台,并且一次写入文件。
我写了一些代码,但我没有成功。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class Utility {
public static void main(String[] args){
try(OutputStream src = new FileOutputStream("C:/Users/baum/Documents/TestText.txt");
InputStream dest = new FileInputStream("C:/Users/baum/Documents/TestText.txt")){
sayHello(src, dest);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sayHello(OutputStream src, InputStream dest)throws IOException{
String t = "Hello World!!!";
OutputStreamWriter out = new OutputStreamWriter(src);
InputStreamReader in = new InputStreamReader(dest);
out.write(t.toCharArray());
out.flush();
in.close();
}
}
try {
for (String line : Files.readAllLines(Paths.get("C:\path\to\text.txt"))) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
这也许是更好的方法
我必须输出方法 sayHello() 两次。 输出应该写入控制台,并且一次写入文件。 我写了一些代码,但我没有成功。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class Utility {
public static void main(String[] args){
try(OutputStream src = new FileOutputStream("C:/Users/baum/Documents/TestText.txt");
InputStream dest = new FileInputStream("C:/Users/baum/Documents/TestText.txt")){
sayHello(src, dest);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sayHello(OutputStream src, InputStream dest)throws IOException{
String t = "Hello World!!!";
OutputStreamWriter out = new OutputStreamWriter(src);
InputStreamReader in = new InputStreamReader(dest);
out.write(t.toCharArray());
out.flush();
in.close();
}
}
try {
for (String line : Files.readAllLines(Paths.get("C:\path\to\text.txt"))) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
这也许是更好的方法