在 Java 中将一个文本文件的内容复制到另一个文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16330960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copying the Contents of One text file to Another in Java
提问by Salman
I am trying to copy the contents of one text file ("1.txt") which contains 2-3 integer numbers (ex: 1 2 3) to another text file ("2.txt") but I am getting the following error upon compilation
我试图将包含 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();
}
}
}
Command prompt:-
命令提示符:-
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
But upon checking the code, I find that the finally() block is properly closed.
但是在检查代码时,我发现 finally() 块已正确关闭。
采纳答案by Luiggi Mendoza
It's finally
, not finally()
:
是finally
,不是finally()
:
try {
//...
} catch(IOException e) {
//...
} finally {
//...
}
By the way, you have an endless loop there:
顺便说一句,你在那里有一个无限循环:
int c=fr.read();
while(c!=-1) {
fw.write(c);
}
You must read the data inside the loop in order to let it finish:
您必须读取循环内的数据才能让它完成:
int c=fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
In the finally
block, your fr
and fw
variables can't be found since they're declared in the scope of the try
block. Declare them outside:
在finally
块中,无法找到您的fr
和fw
变量,因为它们是在try
块的范围内声明的。在外面声明它们:
FileReader fr = null;
FileWriter fw = null;
try {
//...
Now, since they are initialized with null
value, you must also do a null
check before closing them:
现在,由于它们是用null
value初始化的,因此您还必须null
在关闭它们之前进行检查:
finally {
if (fr != null) {
fr.close();
}
if (fw != null) {
fw.close();
}
}
And the close
method on both can throw IOException
that must be handled as well:
并且close
两者上的方法都可以抛出IOException
必须处理的:
finally {
if (fr != null) {
try {
fr.close();
} catch(IOException e) {
//...
}
}
if (fw != null) {
try {
fw.close();
} catch(IOException e) {
//...
}
}
}
In the end, since you don't want to have a lot of code to close a basic stream, just move it into a method that handles a Closeable
(note that both FileReader
and FileWriter
implements this interface):
最后,因为你不希望有很多的代码来关闭一个基本流,只是将其转移到了一种方法,把手一Closeable
(注意,这两个FileReader
并FileWriter
实现了这个接口):
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
//...
}
}
In the end, your code should look like:
最后,您的代码应如下所示:
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) {
//...
}
}
}
Since Java 7, we have try-with-resources
, so code above could be rewritten like:
从 Java 7 开始,我们有try-with-resources
,所以上面的代码可以重写为:
import java.io.*;
class FileDemo {
public static void main(String args[]) {
//this will close the resources automatically
//even if an exception rises
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();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
回答by sanbhat
Its a compilation error
它是一个编译错误
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();
}
}
回答by Elist
A Finally
block shouldn't have the round parentheses.
一个Finally
块不应该有圆括号。
Try:
尝试:
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();
}
}
}
回答by Dhruvil Thaker
Check this javapracticesyou will get better idea. it will help u to understand more about try catch finally.
检查这个javapractices你会得到更好的主意。它将帮助您最终了解有关 try catch 的更多信息。
回答by user2529671
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.your code is not correct > finally block does not takes parenthesis ahead if it. 2.parenthesis always comes in front of methods only. 3.dear your Scope of FileReader and FileWrier objects are end with in the try blocks so you will get one more error in finally block that is fw not found and fr not found 4."throws IOEXception" also mention front of main function
1.你的代码不正确>如果finally块前面没有括号。2.括号总是只出现在方法前面。3.亲爱的你的 FileReader 和 FileWrier 对象的范围以 try 块结尾,所以你会在 finally 块中遇到一个错误,即 fw not found 和 fr not found 4."throws IOEXception" 还提到了 main 函数的前面
回答by Nilesh Jadav
More efficient way is...
更有效的方法是...
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();
}
}
回答by ADHIRAJ KESHRI
Try this code:
试试这个代码:
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);
}
}
}
回答by Fahad Khan
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();
}
}
}
}