您的位置:

java读取字符串,java读取字符串的函数是

本文目录一览:

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();

}

java读取字符串

public class StringDemo1 {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

String str="AAAAA,mmmm,111112121,dddd,11111";

String []st=str.split(",");

for(String sc:st){

System.out.println(sc);

}

}

}

java怎样把一个文本内容读取成字符串

java中可以使用Scanner来读取文件的内容,首先先通过File创建一个文件,再通过Scanner的nextLine()方法读取文本的内容。

具体代码如下所示:

public class Demo {

public static void main(String[] args) {

File file = new File("C:/Users/hp/Desktop/data.txt");

Scanner scanner = null;

try {

scanner = new Scanner(file);

String str = null;

while (scanner.hasNextLine()) {

str += scanner.nextLine() + "\r\n";

}

System.out.println(str);

} catch (Exception e) {

e.printStackTrace();

} finally {

if (scanner != null) {

scanner.close();

}

}

}

}

Scanner的主要功能是简化文本扫描,这个类最实用的地方表现在获取控制台输入。

java怎么从一个文件读取字符串,再存到一个字符串数组里?

首先,可以直接写入string的,这段程序的这种写法很无聊,让你误解了。\x0d\x0a如: out.write(p_send_text);\x0d\x0a\x0d\x0a其次,如果想写入一行并且换行的话,那么得包装一个printwriter,如:\x0d\x0aPrintWriter out = new PrintWriter(FileWriter(file, true));\x0d\x0aout.println(p_send_text);\x0d\x0a\x0d\x0a在Java里,\x0d\x0achar表示一个字符,它可以直接转换为int, byte, long.(ascii/unicode码)\x0d\x0aString表示一串字符,它可以通过某些方法转换成一个数组,如char[], byte[],也可以用其他方法取出其中某个特定位置的字符,如charAt();\x0d\x0a\x0d\x0a与C里面不同,在Java中,通常String用的比较多,char[]基本不用的。