Remove last character/line - java

I have a snippet of code that prints text from a file to a JTextArea called textArea.
Unfortunately the method I'm using goes line by line (not ideal) and so I have to append each line with a \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?

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

(...)
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);
(...)

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 before the new line to display, except for the first line of the file.

The easiest way is to not use BufferedReader.readLine(). For example:
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:
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 DefaultEditorKit for an explanation of how line endings are handled). So you can get rid of the trailing newline with something like this:
// 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);
}

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

Apparently you want a newline between two lines, not after each line. 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' is more complex than 'after'.

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.

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.

Related

How to read two different string format in android

I'm reading data from the input stream where string in two different formats.
One is with a header that is:
Scale id,Rec.No,Date,Time,Bill No.,Item No.,Plu,Name,Qty,Rate,Amount,Void
0,142,17/01/21,17:50,053,3848,001,POTATO ,0.615,50.00,30.75,N
0,143,17/01/21,17:50,053,3849,002,POTATO P ,0.985,36.00,35.46,N
0,144,17/01/21,17:50,053,3850,003,ONION P ,1.550,15.00,23.25,N
Second format is without header:
001,1234560,POTATO ,0,000,K,50.00,15.258,#
002,1234561,POTATO P ,0,000,K,36.00,15.258,#,0.00
003,1234562,ONION P ,0,000,K,15.00,15.258,#,0.00
004,1234563,BR. CHU.CHU. ,0,000,K,28.00,15.258,#,0.00
005,1234564,BR. ROUND ,0,000,K,24.00,15.258,#,0.00
I want to parse these two different formats in two different methods.
Logic and the logic I have used:
public void getReportResponse()throws IOException {
BufferedReader br = null;
str = new StringBuffer();
int bytes = 0;
byte[] packetBytes = new byte[256];
try {
br = new BufferedReader(new InputStreamReader(mmInStream));
String line="";
while ((line = br.readLine()) != null) {
// line = line.trim();
//dataparse.Data(s);
Log.i("DATA in getReportResponse", line);
if (line.matches("Scale id,Rec.No,Date,Time,Bill No.,Item No.,Plu,Name,Qty,Rate,Amount,Void")) {
do {
bytes = mmInStream.read( packetBytes );//READING THE INPUT STREAM
line = new String( packetBytes, 0, bytes );
// append the string in string buffer
str.append( line );
Log.i( TAG,"Report"+str);
// dataparse.ReportData(str.toString());
line="";
} while (str.length()!=-1);
Log.i( TAG,"REPORT"+str);
dataparse.ReportData(str.toString());//this method is for parse value without header after condition
} else {
String data = line.trim();
dataparse.Data(data);//this is working yes//this one is for passing data without header
// Log.i("DATA",line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
But 'if' the condition doesn't work please help me
I would check for the header only once and also only check the first header element
//... removed for brevity
br = new BufferedReader(new InputStreamReader(mmInStream));
String line = br.readLine();
if (line != null && line.startsWith("Scale id")) {
handleHeader(line);
line = br.readLine();
}
while (line != null) {
String data = line.trim();
dataparse.Data(data);
line = br.readLine();
}
//... removed for brevity
Note that all code that is for the if condition has been moved into handleHeader

while(br.readLine() != null)|Window application, java

try {
PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter("D:\\LOL\\" + choice.getSelectedItem() + "\\KDA.txt", true)));
FileReader fr = new FileReader("D:\\LOL\\" + choice.getSelectedItem() + "\\KDA.txt");
BufferedReader br = new BufferedReader(fr);
String suma ;
while(br.readLine() != null){
Integer.parseInt(suma);
suma = 0; //type mismatch: cannot convert from int to String
suma += Double.parseDouble(br.readLine());
textField_4.setText(suma);
}
} catch (Exception e2) {
}
i know that this loop is bad and just need to make a loop that gonna add all numbers in file and then divide by the number of the numbers. i mean when you have file D:\Lol\Plik\KDA.txt and there is 4,0 2,3 12,7 4,3 (for example) and i need to do a loop : 4,0 +2,3 +12,7+4,3/4 = suma textField_setText(suma);
by using buffered reader
I dont know what you are searching for but you have no Integer variable for Integer.parseInt(suma); and then you set sumato zero. Is that what you want? Additional you parse an empty suma-String.
Here is based on the comments the code-Snippet:
String input = br.readLine();
int sum = 0;
int all = 0;
while(input != null){
sum += Double.parseDouble(su.replace(",", "."));
all++;
input = br.readLine();
}
System.out.println(sum/all);
while (br.readLine() != null)
Stop right there. This is already invalid. You've just read a line and thrown it away. What you need to write is
while ((line = br.readLine()) != null)
and then process line inside the loop.
You're also calling readLine() inside the loop, and without checking it for null. It isn't going to give you the same line twice.

I need to print all words that start with the letter "*" in to another output txt (13000 lines) but this program works with like 200 or so

private static void readFile1(String in, String out) throws IOException
{
FileInputStream fis = new FileInputStream(new File(in));
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(out), "utf-8"));
String line = null;
while ((line = br.readLine()) != null)
{
if(line.length() > 0)
{
String[] words = line.split("\\s+");
for(String word : words)
{
if(word.charAt(0)=='*')
{
//System.out.println(word);
writer.write(word);
writer.newLine();
}
}
}
}
br.close();
writer.close();
fis.close();
}
}
Can someone help me with this one?
In cmd i get something like "Exception in thread "main" java.lang.StringIndexOutOfBoundsException:String index out of range:0
The only place you seem to be referencing an index on a string is this if-statement:
if(word.charAt(0)=='*')
Change your if statement to be:
if(!word.isEmpty() && word.charAt(0)=='*')
This will first check if the word is empty and if it is not, then it will look for the proper char
UPDATE
You should add in a NULL check on word as well, just to avoid a NullPointerException
if(word != null && !word.isEmpty() && word.charAt(0)=='*')

Reading a particular line from a text file in Java

What is the most efficient way to extract specific line numbers of data from a text file? For example, if I use the Scanner to parse a file, do I first have to create an array with a length matching the total number of lines in the text file?
If a text file has 30 lines and I only want to work with lines 3, 8, and 12, is there a way to specifically only read those lines?
here is how you do it:
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
int counter = 0;
// This will reference one line at a time
String line = null;
FileReader fileReader = null;
try {
// FileReader reads text files in the default encoding.
fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
counter++;
if(counter == 3 || counter == 8 || counter == 12)
{
// do your code
}
}
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
finally
{
if(fileReader != null){
// Always close files.
bufferedReader.close();
}
}
}
}
here is what you can do. (it is only part of your program, not exactly your program)
int counter 0 =;
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
counter++;
switch(counter){
case 3:
\\ do your code for line no 3
break;
case 8:
\\ do your code for line no 8
break;
case 12:
\\ do your code for line no 12
break;
}
}
br.close();
Try this
try
{
String sCurrentLine;
br = new BufferedReader(new FileReader("File_Path"));
int counter = 0;
while ((sCurrentLine = br.readLine()) != null)
{
counter++;
if (counter == 3 || counter == 8 || counter == 12)
{
System.out.println("" + br.read());
if (counter == 12)
break;
}
}
}
catch (IOException e)
{
System.out.println("Exception " + e);
}
finally
{
try
{
if (br != null)
{
br.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
Regarding the last question: According to this answer, Java 8 enables you to extract specific lines from a file. Examples are provided in that answer.
here you can find the the solution for reading a file according to the line no. This site is the best It contain this code in all the programming languages. And I have given you the java code.
https://www.rosettacode.org/wiki/Read_a_specific_line_from_a_file#Java

Read Specific Line and change String in that Line Java

I have a text file called "Hello.txt"
It has the following contents:
dog
cat
mouse
horse
I want to have a way to check that when reader is reading the lines, if the line equals 2, it replaces "cat" with "hen" and write back to the same file. I have tried this much so far and i dont know where to put the condition to check if line=2, then it does the replacing.My codes are:
import java.io.*;
public class Python_Read_Replace_Line
{
public static void main(String args[])
{
try
{
File file = new File("C:\\Hello.py");
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("C:\\Hello.txt")));
int numlines = lnr.getLineNumber();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + System.lineSeparator();
}
reader.close();
String newtext = oldtext.replaceFirst("cat", "hen");
FileWriter writer = new FileWriter("C:\\Hello.txt");
writer.write(newtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
The file contents should be something like this:
dog
hen
mouse
horse
The code I posted above works because it just replaces cat with hen. I want to have a condition (line number=2), then it replaces it.
Something like this?
int lineCount = 1;
while((line = reader.readLine()) != null)
{
if (lineCount == 2)
oldText += parseCommand.replaceFirst("\\w*( ?)", "hen\1")
+ System.lineSeparator();
//oldText += "hen" + System.lineSeparator();
else
oldtext += line + System.lineSeparator();
lineCount++;
}
Reference.
You could create a variable to keep track of which line number you are at, like so:
int line = 0;
while((line = reader.readLine()) != null)
if (line == 1)
{
oldtext += line + System.lineSeparator();
}
++line;
}

Categories