java 删除最后一个字符/行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/495674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:39:08  来源:igfitidea点击:

Remove last character/line

javaswing

提问by

I have a snippet of code that prints text from a file to a JTextArea called textArea.

我有一段代码可以将文件中的文本打印到名为 textArea 的 JTextArea。

Unfortunately the method I'm using goes line by line (not ideal) and so I have to append each line with a \n

不幸的是,我使用的方法是逐行进行的(不理想),因此我必须在每一行后附加一个 \n

This is fine for now but a new line is created at the end.

现在这很好,但最后会创建一个新行。

The code I have is as follows:

我的代码如下:

class menuOpen implements ActionListener {
    public void actionPerformed(ActionEvent e)
        {
        try {
            File filePath = new File("c:\test.txt");
            FileInputStream file = new FileInputStream(filePath);
            BufferedReader br = new BufferedReader(new InputStreamReader(file));
            String displayText;

            while ((displayText = br.readLine()) != null) {
                textArea.append(displayText + "\n");
            }

        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

Can anyone help me get rid of that last line?

谁能帮我去掉最后一行?

回答by

how about:

怎么样:

text.substring(0,text.lastIndexOf('\n'));

回答by Pierre

(...)
FileReader r= new FileReader(filePath);
StringBuilder b=new StringBuilder();
int n=0;
char array[]=new char[1024];
while((n=r.read(array))!=-1) b.append(array,0,n);
r.close();
String content=b.toString();
textArea.setText(content.substring(0,content.lengt()-1);
(...)

回答by Romain Linsolas

Another idea:

另一个想法:

boolean firstLine = true;
while ((displayText = br.readLine()) != null) {
    if (firstLine) {
        firstLine = false;
    } else {
        textArea.append("\n");
    }
    textArea.append(displayText);
}

The idea is to append a line break beforethe new line to display, except for the first line of the file.

这个想法是要显示的新行之前附加一个换行符,除了文件的第一行。

回答by Jason Day

The easiest way is to not use BufferedReader.readLine(). For example:

最简单的方法是不使用BufferedReader.readLine(). 例如:

BufferedReader in = new BufferedReader(new FileReader(filePath));
char[] buf = new char[4096];
for (int count = in.read(buf); count != -1; count = in.read(buf)) {
    textArea.append(new String(buf, 0, count));
}

EDIT

编辑

I should have seen this before, but a much better way is to let the JTextArea read the file:

我之前应该看到过这个,但更好的方法是让 JTextArea 读取文件:

BufferedReader in = new BufferedReader(new FileReader(filePath));
textArea.read(in, null);

This will still read in the newline at the end, but it will normalize all the line endings in your text (see the javadocs for DefaultEditorKitfor an explanation of how line endings are handled). So you can get rid of the trailing newline with something like this:

这仍然会在最后的换行符中读取,但它将规范化文本中的所有行结尾(有关如何处理行结尾的解释,请参阅javadocDefaultEditorKit)。所以你可以用这样的东西去掉尾随的换行符:

// line endings are normalized, will always be "\n" regardless of platform
if (textArea.getText().endsWith("\n")) {
    Document doc = ta.getDocument();
    doc.remove(doc.getLength() - 1, 1);
}

回答by xtofl

Apparently you want a newline betweentwo lines, not after eachline. This means you should have at least two lines:

显然你想两行之间换行,而不是在每一行之后。这意味着您应该至少有两行:

if (d = br.readLine()) != null ) {
    textArea.append(displayText);
    while (d = br.readLine()) != null ) {
        textArea.append( "\n" + displayText);
    }
}

Of course, it looks more complex. That's because 'between' ismore complex than 'after'.

当然,它看起来更复杂。这是因为“之间”“后”比更复杂。

回答by Aaron Digulla

In your loop:

在你的循环中:

while ((displayText = br.readLine()) != null) {
    if (textArea.length() > 0)
        textArea.append("\n");
    textArea.append(displayText);
}

i.e. if there is already some text in your textarea, insert a newline.

即,如果您的 textarea 中已经有一些文本,请插入一个换行符。

回答by Shawn

How about

怎么样

if (textArea.length > 0) textArea.Text = textArea.Text.Substring(0 ,textArea.Text.Length - 1)

回答by putuyuwono

Its quite easy.. You just need to tweak your code a bit.

它很容易......你只需要稍微调整你的代码。

String displayText = br.readLine(); 
textArea.append(displayText);
while ((displayText = br.readLine()) != null) {
    textArea.append("\n" + displayText);
}

I believe this code produce your desired function at minimum cost.

我相信这段代码以最低的成本产生了你想要的功能。