java中怎样将文件的内容读取成字符串

如题所述

java中有四种将文件的内容读取成字符串

方式一:

Java code

/**

* ä»¥å­—节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

* å½“然也是可以读字符串的。

*/

/* è²Œä¼¼æ˜¯è¯´ç½‘络环境中比较复杂,每次传过来的字符是定长的,用这种方式?*/

public String readString1()

{

try

{

//FileInputStream ç”¨äºŽè¯»å–诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。 

FileInputStream inStream=this.openFileInput(FILE_NAME);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] buffer=new byte[1024];

int length=-1;

while( (length = inStream.read(buffer) != -1)

{

bos.write(buffer,0,length);

// .write方法 SDK çš„解释是 Writes count bytes from the byte array buffer starting at offset index to this stream.

//  å½“流关闭以后内容依然存在

}

bos.close();

inStream.close();

return bos.toString();   

// ä¸ºä»€ä¹ˆä¸ä¸€æ¬¡æ€§æŠŠbuffer得大小取出来呢?为什么还要写入到bos中呢? return new(buffer,"UTF-8") ä¸æ›´å¥½ä¹ˆ?

// return new String(bos.toByteArray(),"UTF-8");       

}

}

方式二:

Java code

方式三:

Java code

方式四:

Java code

/*InputStreamReader+BufferedReader读取字符串  ï¼Œ InputStreamReader类是从字节流到字符流的桥梁*/

/* æŒ‰è¡Œè¯»å¯¹äºŽè¦å¤„理的格式化数据是一种读取的好方式 */

private static String readString4()

{

int len=0;

StringBuffer str=new StringBuffer("");

File file=new File(FILE_IN);

try {

FileInputStream is=new FileInputStream(file);

InputStreamReader isr= new InputStreamReader(is);

BufferedReader in= new BufferedReader(isr);

String line=null;

while( (line=in.readLine())!=null )

{

if(len != 0)  // å¤„理换行符的问题

{

str.append("\r\n"+line);

}

else

{

str.append(line);

}

len++;

}

in.close();

is.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return str.toString();

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-03-09
  String FileName="d:/2.txt";
        File myFile=new File(FileName);
        if(!myFile.exists())
        { 
            System.err.println("Can't Find " + FileName);
        }

        try 
        {
            BufferedReader in = new BufferedReader(new FileReader(myFile));
            String str;
            while ((str = in.readLine()) != null) 
            {
                  System.out.println(str);
            }
            in.close();
        } 
        catch (IOException e) 
        {
            e.getStackTrace();
        }

本回答被提问者采纳
相似回答