我有两个文件,GettysburgAddress.txt,其中写有Gettysburg地址,GettysburgAddressCopy.txt,这是一个空文本文件,我应该填写Gettysburg地址,每个句子,直到它的句号,在另一条线上。 所以我想到了这个
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);
然后,写什么是正确的代码? 非常感谢您给我最好的建议。
答案 0 :(得分:-1)
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class UltimateTextFileOutputDemo
{
public static void main(String[] args)
{
String writtenFileName = "D:\\testdump\\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 = "D:\\testdump\\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);
}
inputStream.useDelimiter("\\.");
while (inputStream.hasNextLine())
{
// setting the period as the delimiter of the read piece of text, I'm sure it gets a single, complete sentence
String line = inputStream.next();
outputStream.println(line);
}
outputStream.close();
inputStream.close();
System.out.println("The Gettysburg Address was written to " + writtenFileName);
}
}