各位csdn网友你们好!
今天上午写了个字符流读取出现了问题,可读但写不进去。
代码块:
public static void copy(String src,String des){
//定义读取的源文件
File srcFile = new File(src);
//定义拷贝的文件
File desFile = new File(des);
try {
//定义文件输入流
FileReader in = new FileReader(srcFile);
//将文件输入流构造到缓存
BufferedReader br = new BufferedReader(in);
//定义输出文件流
FileWriter out = new FileWriter(des);
//将输出文件流构造到缓存
BufferedWriter bw = new BufferedWriter(out);
//读取一行数据
String line = br.readLine();
while(line!=null){
System.out.println(line);//可以输出至控制台 bw.write(line,0,line.length());
bw.write("sorry");//这句都没写进去 bw.newLine();
line = br.readLine();
}
in.close();
out.close();
} catch (FileNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}调用:
public static void main(String[] args) {
// TODO 自动生成方法存根
copy("D:/test.txt","F:/jincheng.txt"); }
今天上午写了个字符流读取出现了问题,可读但写不进去。
代码块:
public static void copy(String src,String des){
//定义读取的源文件
File srcFile = new File(src);
//定义拷贝的文件
File desFile = new File(des);
try {
//定义文件输入流
FileReader in = new FileReader(srcFile);
//将文件输入流构造到缓存
BufferedReader br = new BufferedReader(in);
//定义输出文件流
FileWriter out = new FileWriter(des);
//将输出文件流构造到缓存
BufferedWriter bw = new BufferedWriter(out);
//读取一行数据
String line = br.readLine();
while(line!=null){
System.out.println(line);//可以输出至控制台 bw.write(line,0,line.length());
bw.write("sorry");//这句都没写进去 bw.newLine();
line = br.readLine();
}
in.close();
out.close();
} catch (FileNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}调用:
public static void main(String[] args) {
// TODO 自动生成方法存根
copy("D:/test.txt","F:/jincheng.txt"); }
public void write(String str, int offset, int count) throws IOException {
synchronized (lock) {
if (isClosed()) {
throw new IOException(Msg.getString("K005d")); //$NON-NLS-1$
}
if (count <= 0) {
return;
}
if (offset > str.length() - count || offset < 0) {
throw new StringIndexOutOfBoundsException();
}
if (pos == 0 && count >= buf.length) {
char[] chars = new char[count];
str.getChars(offset, offset + count, chars, 0);
out.write(chars, 0, count);
return;
}
int available = buf.length - pos;
if (count < available) {
available = count;
}
if (available > 0) {
str.getChars(offset, offset + available, buf, pos);
pos += available;
}
if (pos == buf.length) {
out.write(this.buf, 0, this.buf.length);
pos = 0;
if (count > available) {
offset += available;
available = count - available;
if (available >= buf.length) {
char[] chars = new char[count];
str.getChars(offset, offset + available, chars, 0);
out.write(chars, 0, available);
return;
}
str.getChars(offset, offset + available, buf, pos);
pos += available;
}
}
}
} bw.write("sorry",0,"sorry".length());
加入这句龙飞说的bw.flush()轻松搞定!