在Java中将一个文本文件的内容复制到另一个文本文件

时间:2013-05-02 05:30:45

标签: java filereader filewriter

我正在尝试将包含2-3个整数(例如:1 2 3)的一个文本文件(“1.txt”)的内容复制到另一个文本文件(“2.txt”)但我得到了编译时出现以下错误

import java.io.*;
class FileDemo {
    public static void main(String args[]) {
      try {
          FileReader fr=new FileReader("1.txt");
          FileWriter fw=new FileWriter("2.txt");
          int c=fr.read();
          while(c!=-1) {
            fw.write(c);
          }
      } catch(IOException e) {
          System.out.println(e);
      } finally() { 
          fr.close();
          fw.close();
      }
    }
}

命令提示符: -

C:\Documents and Settings\Salman\Desktop>javac FileDemo.java
FileDemo.java:20: error: '{' expected
                finally()
                       ^
FileDemo.java:20: error: illegal start of expression
                finally()
                        ^
FileDemo.java:20: error: ';' expected
                finally()
                         ^
FileDemo.java:27: error: reached end of file while parsing
}
 ^
4 errors

但是在检查代码后,我发现finally()块已正确关闭。

9 个答案:

答案 0 :(得分:28)

它是finally,而不是finally()

try {
    //...
} catch(IOException e) {
    //...
} finally {
    //...
}

顺便说一下,你在那里有一个无限循环:

int c=fr.read();
while(c!=-1) {
    fw.write(c);
}

您必须阅读循环内的数据才能完成:

int c=fr.read();
while(c!=-1) {
    fw.write(c);
    c = fr.read();
}

finally区块中,您的frfw变量无法找到,因为它们是在try块的范围内声明的。在外面宣布它们:

FileReader fr = null;
FileWriter fw = null;
try {
    //...

现在,由于它们是使用null值初始化的,因此在关闭它们之前还必须进行null检查:

finally {
    if (fr != null) {
        fr.close();
    }
    if (fw != null) {
        fw.close();
    }
}

两者上的close方法都可以抛出必须处理的IOException

finally {
    if (fr != null) {
        try {
            fr.close();
        } catch(IOException e) {
            //...
        }
    }
    if (fw != null) {
        try {
            fw.close();
        } catch(IOException e) {
            //...
        }
    }
}

最后,由于您不希望有大量代码来关闭基本流,只需将其移动到处理Closeable的方法中(请注意FileReader和{{} {1}}实现此接口):

FileWriter

最后,您的代码应如下所示:

public static void close(Closeable stream) {
    try {
        if (stream != null) {
            stream.close();
        }
    } catch(IOException e) {
        //...
    }
}

自Java 7以来,我们有import java.io.*; class FileDemo { public static void main(String args[]) { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("1.txt"); fw = new FileWriter("2.txt"); int c = fr.read(); while(c!=-1) { fw.write(c); c = fr.read(); } } catch(IOException e) { e.printStackTrace(); } finally { close(fr); close(fw); } } public static void close(Closeable stream) { try { if (stream != null) { stream.close(); } } catch(IOException e) { //... } } } ,因此上面的代码可以重写为:

try-with-resources

答案 1 :(得分:4)

更有效的方式是......

public class Main {

public static void main(String[] args) throws IOException {
    File dir = new File(".");

    String source = dir.getCanonicalPath() + File.separator + "Code.txt";
    String dest = dir.getCanonicalPath() + File.separator + "Dest.txt";

    File fin = new File(source);
    FileInputStream fis = new FileInputStream(fin);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));

    FileWriter fstream = new FileWriter(dest, true);
    BufferedWriter out = new BufferedWriter(fstream);

    String aLine = null;
    while ((aLine = in.readLine()) != null) {
        //Process each line and add output to Dest.txt file
        out.write(aLine);
        out.newLine();
    }

    // do not forget to close the buffer reader
    in.close();

    // close buffer writer
    out.close();
}
} 

答案 2 :(得分:0)

编译错误

public static void main(String args[])
    {
        try
        {
            FileReader fr=new FileReader("1.txt");
            FileWriter fw=new FileWriter("2.txt");
            int c=fr.read();
            while(c!=-1)
            {
                fw.write(c);
            }
        }
        catch(IOException e)
        {
            System.out.println(e);
        }
        finally // finally doesn't accept any arguments like catch
        {   
            fr.close();
            fw.close();
        }

    }

答案 3 :(得分:0)

Finally块不应该有圆括号。

尝试:

import java.io.*;
class FileDemo
{
    public static void main(String args[])
    {
        try
        {
            FileReader fr=new FileReader("1.txt");
            FileWriter fw=new FileWriter("2.txt");
            int c=fr.read();
            while(c!=-1)
            {
                fw.write(c);
                c = fr.read(); // Add this line
            }
        }
        catch(IOException e)
        {
            System.out.println(e);
        }
        finally
        {   
            fr.close();
            fw.close();
        }

    }
}

答案 4 :(得分:0)

检查此javapractices您将会有更好的想法。 它将帮助你最终了解更多关于try catch的信息。

答案 5 :(得分:0)

import java.io.*;
class FileDemo 
{
public static void main(String args[])throws IOException
{
    FileReader fr=null;
    FileWriter fw=null;
  try 
  {
      fr=new FileReader("1.txt");
      fw=new FileWriter("2.txt");
      int c=fr.read();
      while(c!=-1) 
      {
        fw.write(c);
      }
  } 
  catch(IOException e) 
  {
      System.out.println(e);
  } 
  finally
  { 
      fr.close();
      fw.close();
  }
}
}

1.您的代码不正确>如果是,则finally块不会在前面加括号。 2.parenthesis总是只在方法前面。 3.dear你的FileReader的范围和FileWrier对象在try块中结束,所以你将在finally块中再找到一个错误,找不到fw并且找不到fr 4.“抛出IOEXception”也提到了主要功能的前面

答案 6 :(得分:0)

public function duplicate(Request $request)
{
 

$autoyear = date('Y');
$automonth = date('m');

$autonumber = DB::table('proforms')
            ->select(DB::raw('MAX(autonumber) as autonumber'))
            ->where('automonth', '=', '$automonth')
            ->where('autoyear', '=', '$autoyear')
            ->get();
@$auto = @$autonumber[0]->autonumber;
@$auto[0]++;


$user = User::all('showname','id');
$proform = $this->proform->findOrFail($request->duplicate);
$proforms = Proform::sortable()->paginate(5);
/*
//something like this
$duplicated = Invoice::create([
'invoicenumber' => $proform->proformnumber,
'invoicedate' => $proform->proformdate,
'selldate' => $proform->selldate,
'user_id' => $proform->user_id,
'form_id' => $proform->form_id,
'currency_id' => $proform->currency_id,
'paymentmethod' => $proform->paymentmethod,
'paymentdate' => $proform->paymentdate,
'status' => $proform->status,
'comments' => $proform->comments,
'city' => $proform->city,
'autonumber' => $proform->autonumber,
'automonth' => $proform->automonth,
'autoyear' => $proform->autoyear,
'name' => $proform->name,
'PKWIU' => $proform->PKWIU,
'quantity' => $proform->quantity,
'unit' => $proform->unit,
'netunit' => $proform->netunit,
'nettotal' => $proform->nettotal,
'VATrate' => $proform->VATrate,
'grossunit' => $proform->grossunit,
'grosstotal' => $proform->grosstotal,

]); */

DB::table('invoices')->insert([
['invoicenumber' => $proform->proformnumber,
'invoicedate' => $proform->proformdate,
'selldate' => $proform->selldate,
'user_id' => $proform->user_id,
'form_id' => $proform->form_id,
'currency_id' => $proform->currency_id,
'paymentmethod' => $proform->paymentmethod,
'paymentdate' => $proform->paymentdate,
'status' => $proform->status,
'comments' => $proform->comments,
'city' => $proform->city,
'autonumber' => $proform->autonumber,
'automonth' => $proform->automonth,
'autoyear' => $proform->autoyear,
'name' => $proform->name,
'PKWIU' => $proform->PKWIU,
'quantity' => $proform->quantity,
'unit' => $proform->unit,
'netunit' => $proform->netunit,
'nettotal' => $proform->nettotal,
'VATrate' => $proform->VATrate,
'grossunit' => $proform->grossunit,
'grosstotal' => $proform->grosstotal,
'autonumber' => $number, 
'automonth' => $automonth, 
'autoyear'=> $autoyear],

]);
return view('proforms.show',compact('proform', 'user'))
->with('sukces','Faktura wystawiona');
}

答案 7 :(得分:-1)

public class Copytextfronanothertextfile{

    public static void main(String[] args) throws FileNotFoundException, IOException {

        FileReader fr = null;
        FileWriter fw = null;

        try{
        fr = new FileReader("C:\\Users\\Muzzammil\\Desktop\\chinese.txt");
        fw = new FileWriter("C:\\Users\\Muzzammil\\Desktop\\jago.txt");


        int c;
        while((c = fr.read()) != -1){
            fw.write(c);

        }


    }finally{

           if (fr != null){ 
            fr.close();
        }

           if(fw != null){

              fw.close();
           }
}

}

}

答案 8 :(得分:-2)

试试这段代码:

class CopyContentFromToText {

    public static void main(String args[]){      

        String fileInput = "C://Users//Adhiraj//Desktop//temp.txt";
        String fileoutput = "C://Users//Adhiraj//Desktop//temp1.txt";
        try {
            FileReader fr=new FileReader(fileInput);
            FileWriter fw=new FileWriter(fileoutput);

            int c;
            while((c=fr.read())!=-1) {
                fw.write(c);
            } 
            fr.close();
            fw.close();

        } 
        catch(IOException e) {
            System.out.println(e);
        } 
     }
}