Java中的BufferReader
我对Java中的BufferReader和OutputStream有问题。我的目标是:当你从键盘插入东西时,它会进入文件。我应该如何更正代码Java中的BufferReader,java,outputstream,Java,Outputstream,我对Java中的BufferReader和OutputStream有问题。我的目标是:当你从键盘插入东西时,它会进入文件。我应该如何更正代码 import java.io.*; class IntoFile { public static void main(String[] args) throws Exception{ try { BufferedReader sisse = new BufferedReader(new InputStrea
import java.io.*;
class IntoFile {
public static void main(String[] args) throws Exception{
try {
BufferedReader sisse = new BufferedReader(new InputStreamReader(System.in));
System.out.print ("Insert something: ");
String s = sisse.readLine();
byte[] buf = new byte[1024];
OutputStream valja = new FileOutputStream(new File(args[0]));
String line = null;
while ((line = br.readLine()) != null) {
}
valja.close();
}
catch (IOException e) {
System.out.println ("I/O: " + e);
}
}
}
谢谢 您好,我提供了一个示例代码,您可以通过该代码在用户从键盘输入字符或行后写入文件
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
在我们的.write中传递行(变量)字符串参数,字符串将写入该文件。我将使用Scanner和PrintWriter
C:\Documents and Settings\glowcoder\My Documents>javac Dmitri.java
C:\Documents and Settings\glowcoder\My Documents>java Dmitri
test
woohoo
quit
C:\Documents and Settings\glowcoder\My Documents>more out.txt
test
woohoo
quit
C:\Documents and Settings\glowcoder\My Documents>
代码:
您可以阅读API。对于扫描仪,有一种称为write(Byte[])+1的方法。在大学的时候,我们总是被要求使用一个合适的软件包,这基本上是一个糟糕的扫描仪版本。对于这个答案来说,这绝对是一个很好的类。@这是不幸的混淆。听起来像是教授或助教在炫耀他们的图书馆。如果他们进行尽职调查,他们会抓住机会向学生展示java核心库的强大功能,以及如何有效地使用它们。了解一种语言的核心库(据我估计)是能够说“是的,我知道那种语言”的第一步。是的,我完全同意。在以后的项目中,我总是有意识地选择使用标准库,只是为了熟悉它们。毕竟,两者都不能也不想依赖专有代码。
import java.io.*;
import java.util.*;
class Dmitri {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter("out.txt");
while(in.hasNextLine()) {
String line = in.nextLine();
out.println(line);
out.flush(); // not necessary every time, but simple to do so
if(line.equalsIgnoreCase("QUIT")) break;
}
out.close();
}
}