Java 如何在读取文件时保持格式
我试图将一个.java文件读入一个JTextArea,无论我用什么方法读入该文件,格式都不会被保留。实际的代码还可以,但是注释总是会弄乱。以下是我的尝试Java 如何在读取文件时保持格式,java,Java,我试图将一个.java文件读入一个JTextArea,无论我用什么方法读入该文件,格式都不会被保留。实际的代码还可以,但是注释总是会弄乱。以下是我的尝试 //Scanner: //reads an input file and displays it in the text area public void readFileData(File file) { Scanner fileScanner = null;
//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-也张贴在
Hunter使用JTextArea.read(…)方法。这可能是因为var换行代码被硬编码为“\n”或类似的东西。尝试按如下方式定义换行符:
String newline=System.getProperty("line.separator");
此解决方案更“通用”,但如果使用JTextArea,我将使用camickr解决方案-1,JTextArea的文档使用“\n”表示换行符。在Windows系统上使用line.separator属性将尝试将“\r\n”附加到文本区域。然后将解析出“\r”。JTextArea.read(…)的作用与我上面的任何尝试几乎完全相同。我最终发现JTextArea有setTabSize()和getTabSize()方法,通过将setTabSize()更改为较小的数字,我在原始文档中使用的选项卡显示正常。