如何实现java读取text文件为String?

Python07

如何实现java读取text文件为String?,第1张

BufferedReader br=new BufferedReader(new FileReader(fileName))\x0d\x0aString line=""\x0d\x0aStringBuffer buffer = new StringBuffer()\x0d\x0awhile((line=br.readLine())!=null){\x0d\x0abuffer.append(line)\x0d\x0a}\x0d\x0aString fileContent = buffer.toString()

public class Test {

public static void main(String[] args) {

String str = "张三13312341234"

String result = str.replaceAll("[0-9]", "")//正则表达式

System.out.println(result)

String result2 = new String()

for(char ch : str.toCharArray()){

if(ch >= '0' && ch <= '9'){

}

else{

result2 += ch 

}

}

System.out.println(result2.toString())

}

}

/**

* 主要是输入流的使用,最常用的写法

* @param filePath

* @return

*/

public static String read(String filePath)

{

// 读取txt内容为字符串

StringBuffer txtContent = new StringBuffer()

// 每次读取的byte数

byte[] b = new byte[8 * 1024]

InputStream in = null

try

{

// 文件输入流

in = new FileInputStream(filePath)

while (in.read(b) != -1)

{

// 字符串拼接

txtContent.append(new String(b))

}

// 关闭流

in.close()

}

catch (FileNotFoundException e)

{

// TODO Auto-generated catch block

e.printStackTrace()

}

catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace()

}

finally

{

if (in != null)

{

try

{

in.close()

}

catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace()

}

}

}

return txtContent.toString()

}