How to read a file with a number on each line java - java

I have a spring controller that consumes a multipart/form-data type of request. The user will upload a file that contains a number on each line. Each line will be separated with a new line.. e.g.:
12314
3434234
324545
I currently have the following but not sure if it's efficient:
void readFile(#RequestBody MultipartFile file) throws IOException {
List<String> listOfClientId = new ArrayList<>();
String currentNumber = "";
if(!file.isEmpty()){
InputStream stream = file.getInputStream();
int i = 0;
while( (i=stream.read()) != -1 ) {
if( (char) i != '\n'){
currentNumber = currentNumber + (char) i;
} else {
listOfClientId.add(currentNumber);
currentNumber = "";
}
}
} else {
System.out.println("Malformed filed.");
}
for(String s : listOfClientId){
System.out.println(s);
}
}

You can use BufferedReader like so :
List<String> collect;
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(stream))) {
collect = buffer.lines()
.collect(Collectors.toList());
}
If you want to get List of Numbers instead of String then you can use :
List<Double> collect;
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(stream))) {
collect = buffer.lines()
.map(Double::valueOf) // convert each line(String) to a Double or Integer, it depends on the size of your Numbers
.collect(Collectors.toList());
}

You can use a BufferedReader to read all the lines of the file:
List<String> listOfClientId = new ArrayList<>();
if (!file.isEmpty()) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
String number;
while ((number = reader.readLine()) != null) {
listOfClientId.add(number);
}
}
} else {
System.out.println("Malformed filed.");
}
If you are using Java 8 or higher you can use Java Streams with reader.lines() and map() or filter() the values.

Related

Reading input from a file in Java

I am having the following file have 3 columns , i want read the following file and store them ArrayList , how to read it using Scanner or Buffer reader ?
For Example.
ArrayList<Integert>[][] M = new ArrayList[size][size]
M[1][859].add(1806476)
M[3][800].add(2131700)
M[3][800].add(2734107).. so one
A B C
1 859 [1806476]
3 800 "[2131700, 2734107, 2877209, 2877209]"
4 815 [2883211]
7 815 "[2429412, 2886810, 2886804]"
7 362 [2909301]
7 806 [89573]
7 853 [2182646]
8 800 "[2910937, 2836340, 2884417]"
Basically you want to store it in arrayList. You can use below approach
create a class of fields
class Multi {
int a, b, c;
}
public void addrecords(int i, int j, int k) {
Multi multi = new Multi();
Multi.a = i;
Multi.b = j;
Multi.c = k;
records.add(Multi);
}
List<Multi> records;
//code goes here
private static void parseInput(Map<Pair<Integer, Integer>, List<Integer>> data, String line) {
String[] tmp = line.split(" ");
String result = line.substring(tmp[0].length() + tmp[1].length() + 2);
result = result.replaceAll("\"", "");
result = result.replace(",", "");
result = result.replace("[", "");
result = result.replace("]", "");
List<Integer> t = new ArrayList<>();
for (String a: result.split(" "))
t.add(Integer.parseInt(a));
data.put(new Pair<>(Integer.parseInt(tmp[0]), Integer.parseInt(tmp[1])), t);
}
BufferedReader reader = null;
FileReader fileReader = null;
try {
fileReader = new FileReader("in.txt");
reader = new BufferedReader(fileReader);
String line;
Map<Pair<Integer, Integer>, List<Integer>> data = new HashMap<>();
while ((line = reader.readLine()) != null) {
parseInput(data, line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
if (fileReader != null)
fileReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
plus add try/catch block when u parse String to Integer

Convert String value from a file to integer

I am reading, from a file, integer values that I should use to calculate the function multiple.
However, after converting to integer, it appears that the integer variable doesn't hold them for further calculation.
Any help please?
import java.io.*;
public class Functions {
int values, mul7, mul11, mul13;
public static void main (String []args) {
Functions go = new Functions ();
go.multiple();
// will call functions here
}
public void multiple () {
int a = 7;
int b = 11;
int c = 13;
try {
File inputFile = new File ("JavaInputData.txt");
FileReader fileReader = new FileReader (inputFile);
BufferedReader reader = new BufferedReader (fileReader);
String line = null;
while ((line = reader.readLine()) !=null)
{
values = Integer.parseInt(line);
System.out.println(values);
}
mul7 = values % a;
mul11 = values %b;
mul13 = values %c;
System.out.println(mul7);
reader.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
Perform the calculation and output in the loop body. Something like,
while ((line = reader.readLine()) != null)
{
values = Integer.parseInt(line);
System.out.println(values);
mul7 = values % a;
mul11 = values % b;
mul13 = values % c;
System.out.printf("mul7 = %d, mul11 = %d, mul13 = %d%n", mul7, mul11, mul13);
}
Also, I suggest you use a try-with-resources to close() your Reader;
try (File inputFile = new File ("JavaInputData.txt");
FileReader fileReader = new FileReader (inputFile);
BufferedReader reader = new BufferedReader (fileReader)) {
That way you don't have to call close() explicitly. But, if you're going to call close() explicitly; please do so in a finally block.

Comparing two files in java

I am trying to compare two .txt files (i.e their contents), but when I execute this code my application goes into an infinite loop. Why?
public int compareFile(String fILE_ONE2, String fILE_TWO2)throws Exception
{
File f1 = new File(fILE_ONE2); //OUTFILE
File f2 = new File(fILE_TWO2); //INPUT
FileReader fR1 = new FileReader(f1);
FileReader fR2 = new FileReader(f2);
BufferedReader reader1 = new BufferedReader(fR1);
BufferedReader reader2 = new BufferedReader(fR2);
String line1 = null;
String line2 = null;
int flag=1;
while ((flag==1) &&((line1 = reader1.readLine()) != null)&&((line2 = reader2.readLine()) != null))
{
if (!line1.equalsIgnoreCase(line2))
flag=0;
else
flag=1;
}
reader1.close();
reader2.close();
return flag;
}
I converted your code into a main program. There is no infinite loop in this code.
I am assuming you are comparing 2 text files of a small-ish size.
import java.io.*;
public class Diff {
public static void main(String[] args) throws FileNotFoundException, IOException {
File f1 = new File(args[0]);// OUTFILE
File f2 = new File(args[1]);// INPUT
FileReader fR1 = new FileReader(f1);
FileReader fR2 = new FileReader(f2);
BufferedReader reader1 = new BufferedReader(fR1);
BufferedReader reader2 = new BufferedReader(fR2);
String line1 = null;
String line2 = null;
int flag = 1;
while ((flag == 1) && ((line1 = reader1.readLine()) != null)
&& ((line2 = reader2.readLine()) != null)) {
if (!line1.equalsIgnoreCase(line2))
flag = 0;
}
reader1.close();
reader2.close();
System.out.println("Flag " + flag);
}
}
I ran it on 2 small different text files. This is the output.
javac Diff.java && java Diff a.txt b.txt
Flag 0
If you think you have an infinite loop, the issue might be elsewhere.
The code looks good, no infinite loops. You can remove irrespective check in the code and can update the code as below:
int flag=1;
while (((line1 = reader1.readLine()) != null)&&((line2 = reader2.readLine()) != null))
{
if (!line1.equalsIgnoreCase(line2))
{
flag=0;
break;
}
}
As the return type of the method is integer than it will return 0 if different and 1 if equal.
Assuming text file inputs, an alternative implementation to the while loop:
while (true) // Continue while there are equal lines
{
line1 = reader1.readLine();
line2 = reader2.readLine();
if (line1 == null) // End of file 1
{
return (line2 == null ? 1 : 0); // Equal only if file 2 also ended
}
else if (line2 == null)
{
return 0; // File 2 ended before file 1, so not equal
}
else if (!line1.equalsIgnoreCase(line2)) // Non-null and different lines
{
return 0;
}
// Non-null and equal lines, continue until the input is exhausted
}
The first else if is not necessary, but it is included for clarity purposes. Otherwise, the above code could be simplified to:
while (true) // Continue while there are equal lines
{
line1 = reader1.readLine();
line2 = reader2.readLine();
if (line1 == null) // End of file 1
{
return (line2 == null ? 1 : 0); // Equal only if file 2 also ended
}
if (!line1.equalsIgnoreCase(line2)) // Different lines, or end of file 2
{
return 0;
}
}
The loop should be placed in a try/finally block, to assure that the readers are closed.
Above method by Jess will fail if file2 is same as file1 but has an extra line at the end.
This should work.
public boolean compareTwoFiles(String file1Path, String file2Path)
throws IOException {
File file1 = new File(file1Path);
File file2 = new File(file2Path);
BufferedReader br1 = new BufferedReader(new FileReader(file1));
BufferedReader br2 = new BufferedReader(new FileReader(file2));
String thisLine = null;
String thatLine = null;
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
while ((thisLine = br1.readLine()) != null) {
list1.add(thisLine);
}
while ((thatLine = br2.readLine()) != null) {
list2.add(thatLine);
}
br1.close();
br2.close();
return list1.equals(list2);
}
if you use java8, the code below to compare file contents
public boolean compareTwoFiles(String file1Path, String file2Path){
Path p1 = Paths.get(file1Path);
Path p1 = Paths.get(file1Path);
try{
List<String> listF1 = Files.readAllLines(p1);
List<String> listF2 = Files.readAllLines(p2);
return listF1.containsAll(listF2);
}catch(IOException ie) {
ie.getMessage();
}
}

How to split text file based on startswith

I want to split file as Header with detail in a list based on sequence.
want to split the text file using Header and detail I tried something like this but doesn't help.
I wanted to call previous iteration of iterator but I couldn't...
File :
H>>>>>>
L>>>>>>>
L>>>>>>>
L>>>>>>>
H>>>>>>>
L>>>>>>>
L>>>>>>>
H>>>>>>>
L>>>>>>> ...
I wanted :
List 1 with H , L , L ,L
List 2 with H , L , L
List 3 with H , L
Code Tried :
List<String> poString = new ArrayList<String>();
if(poString !=null && poString.size() > 0)
{
ListIterator<String> iter = poString.listIterator();
while(iter.hasNext())
{
String tempHead = iter.next();
List<String> detailLst = new ArrayList<String>();
if(tempHead.startsWith("H"))
{
while(iter.hasNext())
{
String detailt = iter.next();
if(!detailt.startsWith("H"))
detailLst.add(detailt);
else
{
iter.previousIndex();
}
}
}
}
Try this (untested):
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
List<StringBuilder> myList = new List<StringBuilder>();
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line[0] == 'H')
{
myList.add(sb);
sb = new StringBuilder();
}
sb.append(line[0]);
line = br.readLine();
}
} finally {
br.close();
}
as far as I understood, eventually how many H..lines in your file, how many List<String> would you want to have.
If you don't know the exact number, (in your example, it is 3) then you have a List of List (List<List<String>>).
//read the file, omitted
List<List<String>> myList = new ArrayList<<List<String>>();
List<String> lines = null;
boolean createList = false;
while (line != null) {
if (line.startsWith("H")){
myList.add(lines);
lines = new ArrayList<String>();
}
//if the 1st line of your file not starting with 'H', NPE, you have to handle it
lines.add(line);
line=readnextlineSomeHow(); //read next line
}
the above codes may not work out of box, but it gives you the idea.
Try this, I've tried a little on my own and it works
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
ArrayList<ArrayList<String>> result = new ArrayList<> ();
int numlines =0;
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line.startsWith("H"))
{
result.add(new ArrayList<String>());
result.get(numlines).add("H");
line = br.readLine();
while(line != null && !line.startsWith("H")){
if(line.startsWith("L")) result.get(numlines).add("L");
line = br.readLine();
}
++numlines;
}
else line = br.readLine();
}
} finally {
br.close();
}
You can use this..
public static void main(String a[]) throws Exception
{
ArrayList<String> headers=new ArrayList();
ArrayList<String> lines=new ArrayList();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
File f= new File("inputfile.txt");
Scanner scanner = new Scanner(f);
try {
while (scanner.hasNextLine()){
String ss=scanner.nextLine();
String key= String.valueOf(ss.charAt(0));
if ( map.containsKey(key))
{
ArrayList<String> temp=(ArrayList) map.get(key);
temp.add(ss);
map.put(key, temp);
}
else
{
ArrayList<String> temp= new ArrayList();
temp.add(ss);
map.put(key, temp);
}
}
}
catch(Exception e)
{
throw e;
}
}

convert String to Array in Java

I have a txt file like this:
5
1
3
6
9
I want to read them using java and store all of the numbers into a array.How do I do that? read them in as string and convert to arrray? (how to convert?)
the file only contain ints.
I tried read them into a string
and use this to convert
static public int[] strToA(String str)
{
int len = str.length();
int[] array = new int[len];
for (int i = 0; i < len; i++)
{
array[i] = Integer.parseInt(str.substring(i,i+1));
}
return array;
}
Scanner can help you read your file, and you can use a List or something else to store the info.
After that, you can use this List to convert your Array.
public static Integer[] read2array(String filePath) throws IOException {
List<Integer> result = new ArrayList<Integer>();
RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");
String line = null;
while(null != (line = randomAccessFile.readLine())) {
result.add(new Integer(line));
}
randomAccessFile.close();
return result.toArray(new Integer[result.size()]);
}
Code would be something like this. This is untested code and may have Syntax errors.
Path file = "yourfile";
// open file
try (InputStream in = Files.newInputStream(file);
BufferedReader reader =
new BufferedReader(new InputStreamReader(in))) {
String line = null;
intArr = new int[10]; // bad code could fail if file has more than 10
int i = 0;
while ((line = reader.readLine()) != null) {
intArr[i++] = Integer.parseInt(line); // parse String to int
}
} catch (IOException x) {
System.err.println(x);
}
To use List instead of array change line
intArr = new int[10];
to
List intArr = new ArrayList();
Code would be something like
List intArr = new ArrayList();
while ((line = reader.readLine()) != null) {
intArr.add(Integer.parseInt(line)); // parse String to int
}

Categories

Resources