我必须输出方法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();
}
}
答案 0 :(得分:1)
try {
for (String line : Files.readAllLines(Paths.get("C:\\path\\to\\text.txt"))) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
那可能是更好的方式