gpt4 book ai didi

java - 如何在读取文件时保持格式

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:16:43 25 4
gpt4 key购买 nike

我正在尝试将 .java 文件读入 JTextArea,但无论我使用何种方法读入文件,格式都不会保留。实际代码没问题,但注释总是搞砸了。这是我的尝试。

//Scanner: 
//reads an input file and displays it in the text area
public void readFileData(File file)
{
Scanner fileScanner = null;

try
{
fileScanner = new Scanner(file);
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();

//output is a JTextArea
output.append(line + newline);
}

}
catch(FileNotFoundException fnfe)
{
System.err.println(fnfe.getMessage());
}
}


//Scanner reading the full text at once:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
Scanner fileScanner = null;

try
{
fileScanner = new Scanner(file);

fileScanner.useDelimiter("\\Z");
String fullText = fileScanner.next();

//print to text area
output.append(fullText + newline);

}
catch(FileNotFoundException fnfe)
{
System.err.println(fnfe.getMessage());
}
}


//BufferedReader:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
//Scanner fileScanner = null;

try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(file));

String line = "";
while((line = reader.readLine()) != null)
{
output.append(line + newline);
}
}

有没有办法保持格式不变??

PS - 也发布在 http://www.coderanch.com/t/539685/java/java/keep-formatting-while-reading-files#2448353

猎人

最佳答案

使用 JTextArea.read(...) 方法。

关于java - 如何在读取文件时保持格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6157294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com