Delete last character / line

I have a piece of code that prints text from a file in a JTextArea called textArea.

Unfortunately, the method I use goes line by line (not perfect), so I need to add each line with \ n

Now that’s fine, but at the end a new line is created.

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 someone help me get rid of this last line?

+5
source share
8 answers

What about:

text.substring(0,text.lastIndexOf('\n'));
+6
source
(...)
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);
(...)
+4
source

:

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

, , .

+4

- 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));
}

, - JTextArea :

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

, (. javadocs DefaultEditorKit , ). , :

// 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);
}
+2

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

-, , . , :

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

, . , "" , "".

+1

:

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

. , .

+1

Its pretty 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 that this code creates the desired function at minimal cost.

+1
source

All Articles