【发布时间】:2017-12-14 10:30:26
【问题描述】:
我有两个文件,GettysburgAddress.txt,其中写入了葛底斯堡地址,以及 GettysburgAddressCopy.txt,这是一个空的文本文件,我应该用葛底斯堡地址填写每个句子,直到它的句号,在不同的线上。 所以我想到了这个
import java.io.PrintWriter;`
import java.io.FileNotFoundException;v`
import java.util.Scanner;`
import java.io.File;
public class UltimateTextFileOutputDemo
{
public static void main(String[] args)
{
String writtenFileName = "C:\\Documents and Settings\\GettysburgAddressCopy.txt";
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(writtenFileName);
}
catch (FileNotFoundException e)
{
System.out.println("Error opening the file" + writtenFileName);
System.exit(0);
}
String readFileName = "C:\\Documents and Settings\\GettysburgAddress.txt";
Scanner inputStream = null;
try
{
inputStream = new Scanner(new File(readFileName));
}
catch (FileNotFoundException e)
{
System.out.println("Error opening the file " +
readFileName);
System.exit(0);
}
while (inputStream.hasNextLine())
{
inputStream.useDelimiter("."); // setting the period as the delimiter of the read piece of text, I'm sure it gets a single, complete sentence
String line = inputStream.nextLine();
outputStream.println(line);
}
outputStream.close();
inputStream.close();
System.out.println("The Gettysburg Address was written to " + writtenFileName);
}
}
运行时,如果 GettysburgAddressCopy.txt 尚不存在,程序会正确创建它,但不会用语音填充它。我意识到代码天真都在三行中
inputStream.useDelimiter(".");
String line = inputStream.nextLine();
outputStream.println(line);
但是,正确的代码是什么? 非常感谢您给我最好的建议。
【问题讨论】:
标签: java inputstream outputstream