Reading MultipartFile and being able to break out of loop - java

I have looked at two different ways of reading MultipartFile.
Using the forEach method works, but I can not break out of the forEach loop. I understand I can throw exceptions in the forEach loop to exit the loop but from what I have read it is not good practice.
private boolean validateFile(MultipartFile idFile) {
AtomicBoolean validated = new AtomicBoolean(true);
try {
InputStream inputStream = idFile.getInputStream();
new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.forEach(
line -> {
line = line.trim();
if (line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$")) {
validated.set(false);
}
}
);
} catch (Exception ex) {
validated.set(false);
}
return validated.get();
}
The problem with using forEach is that I can not break out of the loop after executing validated.set(false)
I have also tried using the method below in order to use breaks
private boolean validateFile(MultipartFile idFile) {
boolean validated = true;
InputStream inputStream = null;
BufferedReader br = null;
try {
inputStream = idFile.getInputStream();
br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$")) {
validated = false;
break;
}
}
} catch (Exception e) {
validated = false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return validated;
}
The problem I am facing with the method above is that throw new RuntimeException(e); in the finally block causing sonar errors.
How can I read MultipartFile and being able to break out of the loop? I also don't want to use throws in the finally block since it causes sonar errors.

For your stream-based solution, you can use Stream.noneMatch(). On the first element, which matches the predicate it will stop evaluating the rest of the elements in the stream and return false.
private boolean validateFile(MultipartFile idFile) {
try {
InputStream inputStream = idFile.getInputStream();
return new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.noneMatch(line -> line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$"));
} catch (Exception ex) {
return false;
}
}
For the loop based solution, you can use try-with-resouces statement. It will automatically close the resources for you, so you don't need to do it manually.
private boolean validateFile(MultipartFile idFile) {
boolean validated = true;
try (InputStream inputStream = idFile.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$")) {
validated = false;
break;
}
}
} catch (IOException exc) {
return false;
}
return validated;
}

You could try to use .takeWhile in order to find the first not matching element. It will break the loop in the first occurrence of not matching element and returns the elements until that element.

Related

How to solve infinite readLine while

I have a program and one of the methods I use is for counting the lines a .txt file has and return an integer value. The problem is when I execute it, despite I wrote if my line is == null the while has to stop, the while loop keeps going, ignoring the nulls it gets infinitely.
I don't know what to do to try to solve it.
private int sizeOfFile (File txt) {
FileReader input = null;
BufferedReader count = null;
int result = 0;
try {
input = new FileReader(txt);
count = new BufferedReader(input);
while(count != null){
String line = count.readLine();
System.out.println(line);
result++;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
input.close();
count.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
It has to stop when it detects a null, which means there are no more lines, but it keeps going.
When you instantiate a BuffereReader assign it to count, count will always be non-null and hence will satisfy the while loop:
count = new BufferedReader(input); //count is holding an instance of BufferedReader.
while(count != null){ //here count is non-null and while loop is infinite and program never exits.
Instead use the following code, where the each line will be read and checked whether it is null, if null then the program will exit.:
input = new FileReader(txt);
count = new BufferedReader(input);
String line = null;
while(( line = count.readLine())!= null){ //each line is read and assigned to the String line variable.
System.out.println(line);
result++;
}
If you are using JDK-1.8 you can shorten your code using the Files API:
int result = 0;
try (Stream<String> stream = Files.lines(Paths.get(txt.getAbsolutePath()))) {
//either print the lines or take the count.
//stream.forEach(System.out::println);
result = (int)stream.count();
} catch (IOException e) {
e.printStackTrace();
}
count is your BufferedReader, your loop should be on line! Like,
String line = "";
while (line != null) {
line = count.readLine();
Also, you should use try-with-Resources to close your resources (instead of the finally block). And you could write that while loop more idiomatically. Like,
private int sizeOfFile(File txt) {
int result = 0;
try (BufferedReader count = new BufferedReader(new FileReader(txt))) {
String line;
while ((line = count.readLine()) != null) {
System.out.println(line);
result++;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}

How to fetch a string from a output in console in java and compare it with the expected value

Below is the code:
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The following is my output:
Context successfully set
Script started
LXKADMIN|In/OutBoundValidation|-|50149.11065.26960.11788|inbound=OFF|outbound=OFF
inbound=OFF|outbound=OFF
Script complete
STEP 1: COMPLETED
PASSED: step1
I want to fetch the line 5 "inbound=OFF|outbound=OFF" and check if its value is matching "inbound=OFF|outbound=OFF" then my test case will pass else it will fail.
The TCL Script is:
tcl;
eval {
puts "Script started"
set schemaValidationStr [mql temp query bus LXKADMIN In/OutBoundValidation * select id description dump '|']
puts $schemaValidationStr
set schemaValidation [string range $schemaValidationStr 57 end]
puts $schemaValidation
puts "Script complete"
}
Any suggestion will be really helpful.
If your question is just how to verify that the output returned by your TCL script, contains a specific line, than you might try this:
public static final int CHECK_LINE_NR = 4;
public static final String EXPECTED_LINE_VALUE = "inbound=OFF|outbound=OFF";
public boolean verifyScriptOutput(ChannelExec channel)
throws IOException
{
// Check all lines in output
BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
String line;
int linenr = 0;
while ((line = reader.readLine()) != null)
{
linenr++;
if (linenr == CHECK_LINE_NR)
return (line.equals(EXPECTED_LINE_VALUE));
}
// If we get here, output has less lines
return (false);
} // verifyScriptOutput
The point at which you are reasoning is not possible because you can not access the console and see what is visualized. Instead you should process the input that the console gets, and outputs it, which is the line variable in your case.
If for you is enough to see that inbound=OFF|outbound=OFF you can search that substring in the line like this:
if(line.indexOf("inbound=OFF|outbound=OFF") != -1) {
// you have a match
}
I'm not sure I understood the question, but you might try this:
public static final int CHECK_LINE_NR = 4;
public static final String CHECK_LINE_VALUE = "inbound=OFF|outbound=OFF";
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int linenr;
boolean line_check_passed;
linenr = 0;
line_check_passed = false;
while ((line = reader.readLine()) != null) {
linenr++;
if (linenr == CHECK_LINE_NR)
line_check_passed = line.equals(CHECK_LINE_VALUE);
System.out.println(line);
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public static boolean check(InputStream in, int line, String expected) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int i = 0;
String str;
while ((str = reader.readLine()) != null) {
if (i < line)
i++;
else
return expected.equals(str);
}
return false;
}

Creating file and writing to it (null pointer)

I want to create a method that reads from a file, then creates a file which will then write a certain subset of what was read from but I keep getting a null pointer exception at output.write(line) and I am not sure why?
public void readCreateThenWriteTo(String file, String startRowCount, String totalRowCount) {
BufferedReader br = null;
File newFile = null;
BufferedWriter output = null;
StringBuilder sb = null;
int startRowCountInt = Integer.parseInt(startRowCount);
int totalRowCountInt = Integer.parseInt(totalRowCount);
try {
br = new BufferedReader(new FileReader(file));
sb = new StringBuilder();
newFile = new File("hiya.txt");
output = new BufferedWriter(new FileWriter(newFile));
String line = "";
int counter = 0;
while (line != null) {
line = br.readLine();
if (startRowCountInt <= counter && counter <= totalRowCountInt) {
System.out.println(line);
output.write(line);
}
counter++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
LOGGER.info("File was not found.");
e.printStackTrace();
} finally {
// Should update to Java 7 in order to use try with resources and then this whole finally block can be removed.
try {
if ( br != null ) {
br.close();
}
if ( output != null ) {
output.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
LOGGER.info("Couldn't close BufferReader.");
e.printStackTrace();
}
}
}
You need to check the result of readLine() before you enter the loop:
while ((line = br.readLine()) != null) {
if (startRowCountInt <= counter && counter <= totalRowCountInt) {
System.out.println(line);
output.write(line);
}
counter++;
}

How to use variable in a while loop outside of the loop in java?

I have a variable that is set in a while loop because it is reading from a file. I need to access and use the code from the outside of the loop, because I'm using the variable in an if statement and the if statement can't be in the while loop or else it will be repeated multiple times. Here is my code.
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\Brandon\\Desktop\\" + Uname + ".txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}if(sCurrentLine.contains(pwd)){System.out.println("password accepted");}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Put your if statement inside your for loop, but use a break:
while...
if(sCurrentLine.contains(pwd)){
System.out.println("password accepted");
break;
}
This breaks out of the for loop, so that once the password is found, it stops looping. You can't really move that if-check outside of the loop, because you want to check every line for the password until it is found, right?
If you do that, you don't need to move the sCurrentLine variable out of the loop. You also might want to doublecheck if you want to do sCurrentLine.equals(pwd) instead of using contains.
You already have sCurrentLine declared outside your while loop. The problem is that you keep using it again and again for the next line. If you still want it to print the file and what you are trying to do is remember that the password was found or what line it was found in try this:
BufferedReader br = null;
boolean pwdFound = false;
String pwdLine = "";
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\Brandon\\Desktop\\" + Uname + ".txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
if(sCurrentLine.contains(pwd)){
System.out.println("password accepted");
pwdFound = true;
pwdLine = sCurrentLine;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
boolean flag = false;
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.contains(pwd))
{
flag = true;
break;
}
}
if(flag){System.out.println("password accepted");}

Can not print out a set in Java

i am writing a program that read in two text files and find the differences
but for some reason, i can not print the result set. I checked for lot of times and still couldn't find the reason and i hope you guys can help me out. here is the code.
the problem occur at the for each to print the set.
import java.io.*;
import java.util.*;
public class PartOne {
public static void readFileAtPath(String filePathOne, String filePathTwo) {
// Lets make sure the file path is not empty or null
if (filePathOne == null || filePathOne.isEmpty()) {
System.out.println("Invalid File Path");
return;
}
if (filePathTwo == null || filePathTwo.isEmpty()) {
System.out.println("Invalid File Path");
return;
}
Set<String> newUser = new HashSet<String>();
Set<String> oldUser = new HashSet<String>();
BufferedReader inputStream = null;
BufferedReader inputStream2 = null;
// We need a try catch block so we can handle any potential IO errors
try {
// Try block so we can use ‘finally’ and close BufferedReader
try {
inputStream = new BufferedReader(new FileReader(filePathOne));
inputStream2 = new BufferedReader(new FileReader(filePathTwo));
String lineContent = null;
String lineContent2 = null;
// Loop will iterate over each line within the file.
// It will stop when no new lines are found.
while ((lineContent = inputStream.readLine()) != null) {
// Here we have the content of each line.
// For now, I will print the content of the line.
// System.out.println("Found the line: " + lineContent);
oldUser.add(lineContent);
}
while ((lineContent2 = inputStream.readLine()) != null) {
newUser.add(lineContent2);
}
Set<String> uniqueUsers = new HashSet<String>(newUser);
uniqueUsers.removeAll(oldUser);
}
// Make sure we close the buffered reader.
finally {
if (inputStream != null)
inputStream.close();
if (inputStream2 != null)
inputStream2.close();
}
for (String temp : uniqueUsers) {
System.out.println(temp);
}
} catch (IOException e) {
e.printStackTrace();
}
}// end of method
public static void main(String[] args) {
String filePath2 = "userListNew.txt";
String filePath = "userListOld.txt";
readFileAtPath(filePath, filePath2);
}
}
Your problem is scope. You define the set inside your try block but then you attempt to access it from outside that block. You must define all variables within the same scope you want to use that variable.
Move the definition of uniqueUsers to before your try block.
*Edit in response to your comment.
You are reading from the same input stream twice. The second while loop should be reading from inputStream2.
Try this
try {
// Try block so we can use ‘finally’ and close BufferedReader
try {
inputStream = new BufferedReader(new FileReader(filePathOne));
inputStream2 = new BufferedReader(new FileReader(filePathTwo));
String lineContent = null;
String lineContent2 = null;
// Loop will iterate over each line within the file.
// It will stop when no new lines are found.
while ((lineContent = inputStream.readLine()) != null) {
// Here we have the content of each line.
// For now, I will print the content of the line.
// System.out.println("Found the line: " + lineContent);
oldUser.add(lineContent);
}
while ((lineContent2 = inputStream.readLine()) != null) {
newUser.add(lineContent2);
}
Set<String> uniqueUsers = new HashSet<String>(newUser);
uniqueUsers.removeAll(oldUser);
for (String temp : uniqueUsers) {
System.out.println(temp);
}
}
// Make sure we close the buffered reader.
finally {
if (inputStream != null)
inputStream.close();
if (inputStream2 != null)
inputStream2.close();
}
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources