while(br.readLine() != null)|Window application, java - 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.

Related

Get current line number from bufferedReader

I have different text files I would like to read, and I am using BufferedReader for it like this:
int theMax = 0;
int theTypes = 0;
int []theSlices = {};
/*
INPUT1:
17 4
2 5 6 8
INPUT2:
100 10
4 14 15 18 29 32 36 82 95 95
*/
try {
FileReader reader = new FileReader("INPUT1.in");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
System.out.println(numbers[0]);
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
;
My problem is that I would like to set the values for theMax, theTypes & theSlices but for that I need to get the current line number and I have no idea how to do that. Reading the file works and println(numbers[0] prints 17 and 2. I am kind of stuck here so I am happy for every help.
Example for INPUT1:
theMax = 17
theTypes = 4
theSlices = 2 5 6 8
Very simple: you keep track yourself.
String line;
int currentLine = 0;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
System.out.println("Linenumber " + currentLine);
System.out.println(numbers[0]);
System.out.println(line);
currentLine ++;
}
reader.close();
Not sure I totally understand what you are after, but for just keeping track of the line numbers, create a variable that you increment in your while loop
i.e.
try {
FileReader reader = new FileReader("INPUT1.in");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
long currentLineNr = 0;
while ((line = bufferedReader.readLine()) != null) {
currentLineNr++;
String[] numbers = line.split(" ");
System.out.println(numbers[0]);
System.out.println(line);
//Use the currentLineNr how you like
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
First of all, as far as I know (and having read the official Java documentation for it here - https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html), the BufferedReader class does not in itself give you a mechanism (e.g. a getCurrentLine() method) to determine the current line.
However, there is absolutely nothing stopping you from keeping track of current line number yourself through, say, a counter variable.
Therefore, the relevant section of your code would look like:
int currentLine = 0;
while ((line = bufferedReader.readLine()) != null) {
currentLine++;
String[] numbers = line.split(" ");
/* NOTE: this can be numbers.length >= 2 if you don't care to enforce
having exactly 2 numbers as the first line
*/
if(currentLine == 1 && numbers.length == 2) {
theMax = Integer.valueOf(numbers[0]);
theTypes = Integer.valueOf(numbers[1]);
} else {
for(int index = 0; index < numbers.length; index++) {
theSlices[index] = Integer.valueOf(numbers[index]);
}
}
}
// do something with read values
I would also like to mention that your code could be improved here and there, for example:
You can replace your try with a try-with-resources, such that your readers are managed/closed automatically even if an exception occurs.
If you decide not to use try-with-resources, then you'll need to move your reader.close() method call in a finally block, because if an exception actually occurs you are never closing your resource.
These 2 lines
FileReader reader = ;
BufferedReader bufferedReader = new BufferedReader(reader);
can be simplified into:
BufferedReader bufferedReader = new BufferedReader(new FileReader("INPUT1.in"));
and then you only need to manage the bufferedReader instance if sticking to try instead of try-with-resources.
Hope this helps.
PS: not saying that my code snippet above is perfect, I'm sure it can be written more cleanly
Use java.io.LineNumberReader.
LineNumberReader is a subclass of BufferedReader that keeps track of line numbers. It provides a getLineNumber() method for getting the current line number.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/LineNumberReader.html
Example:
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class Example {
public static void main(String[] args) throws IOException {
try (FileReader fr = new FileReader("input.txt");
LineNumberReader r = new LineNumberReader(fr)) {
String next;
while ((next = r.readLine()) != null) {
System.out.println("line number " + r.getLineNumber() + " = " + next);
}
}
}
}

how to split 100 lines in a xml file which has n number of lines and add it to sub files using java

I am new to the programming please help me regarding this scenario.
I am trying to design a code for a program
I have a xml files which contains X number of lines and i need to put first 100 lines of that file to another sub file and next to another sub file and so on up to the end. naming convention should be like file1, file2,....
Input files will be of 5000, 10000 or even more lines
I need a dynamic code for this scenario using dom parser
i designed a code for a file with constant lines.
import java.io.*;
public class splitting
{
public static void main(String args[])throws Exception
{
int count = 0;
BufferedReader br = null;
FileWriter fileWriter1 = new FileWriter("C:\\senderoutput1.txt");
FileWriter fileWriter2 = new FileWriter("C:\\senderoutput2.txt");
FileWriter fileWriter3 = new FileWriter("C:\\senderoutput3.txt");
FileWriter fileWriter4 = new FileWriter("C:\\senderoutput4.txt");
try {
String currentLine;
br = new BufferedReader(new FileReader("C:\\senderinput.txt"));
while ((currentLine = br.readLine()) != null)
{
count++;
if (count <= 100)
{
fileWriter1.write(currentLine + System.getProperty("line.separator", "\r\n"));
} else if (count > 100 && count <= 200)
{
fileWriter2.write(currentLine + System.getProperty("line.separator", "\r\n"));
}else if (count > 200 && count <= 300)
{
fileWriter3.write(currentLine + System.getProperty("line.separator", "\r\n"));
}else if (count > 300 && count <= 400)
{
fileWriter4.write(currentLine + System.getProperty("line.separator", "\r\n"));
}
}
} finally
{
if (br != null)
{
br.close();
}
fileWriter1.close();
fileWriter2.close();
fileWriter3.close();
fileWriter4.close();
System.out.println("File Splitting was successful!!!");
}
}
}
this code is for the file which has 400 lines.
how to do it for n number of lines?
You can do something like this to achieve what you are trying to achieve:
BufferedReader br = null;
FileWriter fileWriter = new FileWriter("C:\\senderoutput1.txt");
try {
String currentLine = null;
br = new BufferedReader(new FileReader("C:\\senderinput.txt"));
while ((currentLine = br.readLine()) != null) {
/* Increment Counter */
++count;
/* Write Text To File */
fileWriter.write(currentLine + System.getProperty("line.separator", "\r\n"));
/* Check Split Condition */
if (count % 100 == 0) {
/* Close Already Open File */
fileWriter.close();
/* Point To New File */
fileWriter = new FileWriter("C:\\senderoutput" + (count/100 + 1) + ".txt");
}
}
/* Close Last Open File */
fileWriter.close();
} finally {
if (br != null) {
br.close();
}
System.out.println("File Splitting Completed Successfully!!!");
}
Please note that this is just to give you an idea and you can modify it as per your needs.
Beginner approach:
1) Read the next line in a loop.
2) Increment a counter & append the current line into a String.
3) Every time the counter hits a new 100 decimal value,
write out the String (which contains the collection of lines)
to a new file.
4) Clear the string.
I believe it's much better to make a description, then giving out code, especially for beginners.
Write the n lines in m no. of files (as User input) :
You should try this easiest code to achieve this dynamically.
I am using here Buffered Reader, Buffered Writer and java streams to get this :
//Code here :
String curpath = System.getProperty("user.dir");
List<String> list = null;
BufferedWriter bw1 = null;
Scanner sc = new Scanner(System.in);
System.out.println("How many lines you want per file, Please Enter");
String nfr = sc.nextLine();
int nfr1 = Integer.parseInt(nfr);
System.out.println("How many file you want, Please Enter");
String nfr2 = sc.nextLine();
int nfr3 = Integer.parseInt(nfr2);
sc.close();
int count = 1;
int i = nfr1; // no. of lines per file
int b = 0;
for (int j = 1; j <= nfr3; j++) { // nfr3 -- no. of files create
BufferedReader br = new BufferedReader(new FileReader(curpath + "//datafile.txt"));
list = br.lines().skip(b).limit(i).collect(Collectors.toList());
b = count * i; //skip the lines
File file1 = new File(curpath + "//Split_Line" + "//file" + j + ".txt" + " ");
file1.getParentFile().mkdirs();
file1.createNewFile();
bw1 = new BufferedWriter(new FileWriter(file1));
for (String record : list)
bw1.write((record + System.lineSeparator()));
br.close();
bw1.flush();
count++;
}
System.out.println("Split_line file complete");
bw1.close();
I suppose, it would be helpful to you. If you want to suggest anything to improve code. please comment

How do I force my while loop that is reading a line to not stop before 3 empty lines?

I have this while loop that is reading a BufferedReader.
BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println (line);
}
I know it is going to stop as soon as the line is null, but in this case (the data I am reading), there are some new lines and then the data continues.
Hence, I want the while loop to stop executing once it has found 3 empty lines in a row (for then I am sure that the data is finished).
Thank you
Improving #user2004685's answer, you can count the number of empty lines:
BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));
int emptyCount = 0;
String line;
while (emptyCount < 3 && (line = br.readLine()) != null) {
System.out.println (line);
/* Track Empty Lines Count */
if(String.isEmpty(line)) {
emptyCount++;
} else {
emptyCount = 0;
}
}
Don't forget to reset emptyCount to 0, otherwise it'll exit too soon in case you'd have line,emty,line,empty,line,empty,line,empty,line,empty...
Keep a track of the empty lines and add an additional condition to your loop.
Try this piece of code:
BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));
int emptyCount = 0;
String line = null;
while (emptyCount < 3 && (line = br.readLine()) != null) {
System.out.println (line);
/* Track Empty Lines Count */
if(String.isEmpty(line)) {
emptyCount++;
} else {
emptyCount = 0;
}
}
Update:
I have overlooked "3 empty lines after each other". Updated the solution as per Gavriel's comment.
Thanks Gavriel!

Read first character on each line in a file

I have a file in this format:
0 2 4
3 2 4
3 5 2
1 8 2
My aim is to read the first line on each file and store it in a array. So at the end I should have 0,3,3,1
I thought one approach would be, read the line until we encounter a space and save that in a array...but it would keep on reading 2 and 4 after
Is there a efficient way of doing this, my cod is shown below:
openandprint()
{
int i = 0;
try (BufferedReader br = new BufferedReader(new FileReader("final.txt")))
{
String line;
while ((line = br.readLine()) != null) {
int change2Int=Integer.parseInt(line.trim());
figures [i] = change2Int;
i++;
}
}
catch (Exception expe)
{
expe.printStackTrace();
}
}
Using a Scanner would make the code considerably cleaner:
private static openandprint() throws IOException {
int i = 0;
try (Scanner s = new Scanner("final.txt"))) {
String line;
while (s.hasNextLine()) {
int change2Int = s.nextInt();
s.nextLine(); // ignore the rest of the line
figures [i] = change2Int;
i++;
}
}
}
Try
int change2Int=Integer.parseInt((line.trim()).charAt(0)-'0');
or
int change2Int=Character.getNumericValue(line.charAt(0));
with your approch you are reading the whole line and parsing it to int which will give you NumberFormatException because of the space between the digits.
BufferedReader br = ...;
String line = null;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" ");
int next = Integer.parseInt(parts[0]);
System.out.println("next: " + next);
}

Remove last character/line

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.

Categories