JAVA FileReader和FileWriter的小问题
代码如下:importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;publ...
代码如下:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class WriterReader
{
public static void main(String[] args)
{
copy_one();
}
public static void copy_one()
{
FileWriter fw=null;
FileReader fr=null;
try
{
fr=new FileReader("F:\\CharTesy.java");
fw=new FileWriter("F:\\CharTesy_copy.txt");
char [] buf=new char[1024];
int len=0;
while((len=fr.read())!=-1)
{
fw.write(buf, 0, len);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(fr!=null)
try
{
fr.close();
}
catch(IOException e)
{
e.printStackTrace();
}
if(fw!=null)
try
{
fw.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
错误如下:
Exception in thread "main" java.lang.IndexOutOfBoundsException
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at WriterReader.copy_one(WriterReader.java:25)
at WriterReader.main(WriterReader.java:10)
问题:什么原因?
额已解决,太粗心了,少读了个buf 展开
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class WriterReader
{
public static void main(String[] args)
{
copy_one();
}
public static void copy_one()
{
FileWriter fw=null;
FileReader fr=null;
try
{
fr=new FileReader("F:\\CharTesy.java");
fw=new FileWriter("F:\\CharTesy_copy.txt");
char [] buf=new char[1024];
int len=0;
while((len=fr.read())!=-1)
{
fw.write(buf, 0, len);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(fr!=null)
try
{
fr.close();
}
catch(IOException e)
{
e.printStackTrace();
}
if(fw!=null)
try
{
fw.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
错误如下:
Exception in thread "main" java.lang.IndexOutOfBoundsException
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at WriterReader.copy_one(WriterReader.java:25)
at WriterReader.main(WriterReader.java:10)
问题:什么原因?
额已解决,太粗心了,少读了个buf 展开
展开全部
读写文件?我是这么写的
读文件:
InputStreamReader read = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(read);
String linetxt = null;
while((linetxt=bufferedReader.readLine())!=null){
list.add(linetxt.trim());
}
read.close();
bufferedReader.close();
写文件:
public static void log(String str,String filename) {
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileWriter(filename, true));
pw.println(str);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.flush();
pw.close();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询