java给文件字符串
⑴ java怎么将字符串写入到文件
使用Java中的File类,url为文件的绝对地址,str为输入的字符串内容。
代码如下图所示:
String str="i love china!"
File txt=new File("url");
if(!txt.exists()){
txt.createNewFile();
}
byte bytes[]=new byte[512];
bytes=str.getBytes(); //新加的
int b=str.length(); //改
FileOutputStream fos=new FileOutputStream(txt);
fos.write(bytes,0,b);
fos.close();
⑵ 如何java向文件写入字符串
BufferedReader buff = new BufferedReader(new FileReader("abc.txt"));
String str = "asdfsfas";
for (int i = 0;i < str.length();i++)
buff.write(str.charAt(i));
buff.close();
⑶ java中怎样将文件的内容读取成字符串
java中有四种将文件的内容读取成字符串
方式一:
Java code
/**
*以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*当然也是可以读字符串的。
*/
/*貌似是说网络环境中比较复杂,每次传过来的字符是定长的,用这种方式?*/
publicStringreadString1()
{
try
{
//FileInputStream用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用FileReader。
FileInputStreaminStream=this.openFileInput(FILE_NAME);
ByteArrayOutputStreambos=newByteArrayOutputStream();
byte[]buffer=newbyte[1024];
intlength=-1;
while((length=inStream.read(buffer)!=-1)
{
bos.write(buffer,0,length);
//.write方法SDK的解释是m.
//当流关闭以后内容依然存在
}
bos.close();
inStream.close();
returnbos.toString();
//为什么不一次性把buffer得大小取出来呢?为什么还要写入到bos中呢?returnnew(buffer,"UTF-8")不更好么?
//returnnewString(bos.toByteArray(),"UTF-8");
}
}
方式二:
Java code
方式四:
Java code
/*InputStreamReader+BufferedReader读取字符串,InputStreamReader类是从字节流到字符流的桥梁*/
/*按行读对于要处理的格式化数据是一种读取的好方式*/
()
{
intlen=0;
StringBufferstr=newStringBuffer("");
Filefile=newFile(FILE_IN);
try{
FileInputStreamis=newFileInputStream(file);
InputStreamReaderisr=newInputStreamReader(is);
BufferedReaderin=newBufferedReader(isr);
Stringline=null;
while((line=in.readLine())!=null)
{
if(len!=0)//处理换行符的问题
{
str.append(" "+line);
}
else
{
str.append(line);
}
len++;
}
in.close();
is.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returnstr.toString();
}