Java-复制到新的txt文件
这个程序创建的新test1.txt文件是完全空的,原始文件test.txt中填充了类似“50 3 21 57 10 20”的内容,基本上是带空格的整数Java-复制到新的txt文件,java,text,copy,Java,Text,Copy,这个程序创建的新test1.txt文件是完全空的,原始文件test.txt中填充了类似“50 3 21 57 10 20”的内容,基本上是带空格的整数 import java.util.*; import java.io.*; class AddOneToInts { public static void main(String [] args) throws IOException { Scanner scan = new Scanner(new Buffer
import java.util.*;
import java.io.*;
class AddOneToInts
{
public static void main(String [] args) throws IOException
{
Scanner scan = new Scanner(new BufferedReader(new FileReader( "test.txt" )));
BufferedWriter writer = new BufferedWriter(new FileWriter( "text1.txt" ));
boolean cont = true;
String temp;
while (cont) {
if (scan.hasNextInt()) {
temp = (scan.nextInt()+1) + " ";
writer.write(temp);
} else break;
}
}
}
您必须关闭Java流才能将其内容刷新到文件中:
Scanner scan = new Scanner(new BufferedReader(new FileReader( "test.txt" )));
BufferedWriter writer = new BufferedWriter(new FileWriter( "text1.txt" ));
boolean cont = true;
String temp;
while (cont) {
if (scan.hasNextInt()) {
temp = (scan.nextInt()+1) + " ";
writer.write(temp);
} else break;
}
writer.close(); // <<------------------------
Scanner scan=新的扫描仪(新的BufferedReader(新的文件阅读器(“test.txt”));
BufferedWriter=新的BufferedWriter(新的文件编写器(“text1.txt”);
布尔控制=真;
字符串温度;
while(续){
if(scan.hasNextInt()){
temp=(scan.nextInt()+1)+”;
writer.write(临时);
}否则就断了;
}
writer.close();// 关闭流的最佳实践:
import java.util.*;
import java.io.*;
public class AddOneToInts
{
public static void main(String [] args) throws IOException
{
Scanner scan = null;
BufferedWriter writer = null;
try
{
scan = new Scanner(new BufferedReader(new FileReader( "test.txt" )));
writer = new BufferedWriter(new FileWriter( "text1.txt" ));
boolean cont = true;
String temp;
while (cont)
{
if (scan.hasNextInt())
{
temp = (scan.nextInt()+1) + " ";
writer.write(temp);
}
else break;
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(writer != null)
{
try
{
writer.close();
}
catch(IOException e) {}
}
if(scan != null)
{
try
{
scan.close();
}
catch(IOException e) {}
}
}
}
}
尽管Apache Commons IO有一个可以“无声关闭流”的函数,因此您不必在finally块中编写第二个try-catch块。我可以看到问题已经为询问者回答了。为了让大家稍后看到类似的流相关问题,Think将尝试添加一些更清晰的内容。缺少的是一个有效的解决方案
writer.flush()
缓冲写入程序(或任何缓冲的写入程序)在其缓冲区已满时自动刷新。我想正常尺寸大约是8K。这就是为什么在这种情况下它没有自动刷新
writer.close()
执行缓冲区flush()
。所以close()起作用了
但是,对于进程退出时的本机流,它会自动执行close()
。在这里,它不是本地缓冲区,而是更高级别的缓冲区。为了说明示例中是否进行了以下替换
//OutputStreamWriter writer=new OutputStreamWriter(new FileOutputStream("text1.txt"));
OutputStream out=new FileOutputStream("text1.txt");
及
这个例子甚至不需要flush()或close(),尽管这是正确的做法。在循环结束后关闭writer。
//writer.write(temp);
out.write(temp.getBytes());