非常感谢!! 可是我执行下面程序时为什么会报错呢? public class B { BufferedReader in = new BufferedReader(new FileReader( "D:\\test.txt ")); String s,s2 = new String(); while((s = in.readLine()) != null) s2 += s+"\n"; in.close();
public static void main(String args[]) { B b = new B(); System.out.println(s2); } }
import java.io.*;public class B {
public String readfile() throws IOException{ BufferedReader in = new BufferedReader(new FileReader( "D:\\test.txt ")); String s,s2 = new String(); while((s = in.readLine()) != null) s2 += s+"\n"; in.close(); return s2; } public static void main(String args[]) { B b = new B(); try { System.out.println(b.readfile()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
s2是class B里的一个字段,不能直接调用。System.out.print(b.s2);
import java.io.*; class read { public static void main(String[] args) { int i; try { FileInputStream in = new FileInputStream("D:\\test.txt"); while((i=in.read())!=-1) { System.out.print((char)i); } in.close(); } catch(Exception e) { e.printStackTrace(); } }
String s, s2 = new String();
while((s = in.readLine()) != null)
s2 += s + "\n";
in.close();
System.out.println(s2);
2. 应该是一样的, 可以试试.
FileReader fr = null;
try {
fr = new FileReader("d:\\test.txt");
br = new BufferedReader(fr);
String str = null;
StringBuffer sb = new StringBuffer();
while ((str = br.readLine()) != null) {
sb.append(str + "\n");
}
System.out.println(sb.toString());
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
}
FileReader f = new FileReader("c:\\MYP.dat");
BufferedReader br = new BufferedReader(f);
String str;
while((str=br.readLine())!=null) {
System.out.print(str);
}
br.close();
f.close();
redline()是整行读取,如果只读取字符,可以用FileReader的read()方法。
可是我执行下面程序时为什么会报错呢?
public class B
{
BufferedReader in = new BufferedReader(new FileReader( "D:\\test.txt "));
String s,s2 = new String();
while((s = in.readLine()) != null)
s2 += s+"\n";
in.close();
public static void main(String args[])
{
B b = new B();
System.out.println(s2);
}
}
{
public String readfile() throws IOException{
BufferedReader in = new BufferedReader(new FileReader( "D:\\test.txt "));
String s,s2 = new String();
while((s = in.readLine()) != null)
s2 += s+"\n";
in.close();
return s2;
}
public static void main(String args[])
{
B b = new B();
try {
System.out.println(b.readfile());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class read
{
public static void main(String[] args)
{
int i;
try
{
FileInputStream in = new FileInputStream("D:\\test.txt");
while((i=in.read())!=-1)
{
System.out.print((char)i);
}
in.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
不过如果文件中有汉字的话会是乱码