Reading input from a file in Java - 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

Related

Array returning null

I'm trying to read into a csv file and placing the line into an array. But when I print the array out it is null.
Here is the code:
public static String[] readFile(String inFilename)
{
int lineTotal = getLineNum(inFilename);
if (lineTotal == 0)
{
System.out.println("The file is empty ");
}
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String[] resultArrayOne = new String[lineTotal + 1];
String line;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
int lineNum;
String[] resultArray = new String[lineTotal];
String info;
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
info = line;
System.out.println(info);
resultArray[lineNum] = info;
lineNum++;
}
fileStrm.close(); //Clean up the stream
resultArrayOne = resultArray;
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return resultArrayOne;
}
When printing out the line before placing it into the array the return is fine, but when placed into the array it become null.
edit:
Here is the full FileIO code:
public static String[] Import()
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the File Name: ");
String fileName = sc.nextLine();
int length = getLineNum(fileName);
String[] array = new String[length+1];
array = readFile(fileName);
return array; //array is just strings
}
public static int getLineNum(String inFilename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
lineNum++;
}
fileStrm.close(); //Clean up the stream
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return lineNum;
}
I'm not too sure how to insert a sample file but it is something like this:
SHOP1, STORE2, 45
SHOP2, SHOP1, 67
STORE6, SHOP1, 90
...
edit 2:
I added the code that uses this
String[] locationArrayOne = new String[1000];
locationArrayOne = FileIO.Import();
for (int yyy = 0; yyy < locationArrayOne.length; yyy++)
{
System.out.print(locationArray[yyy]);
}
Your code looks fine but here is how I would debug the problem:
Before lineNum++, I will print the value of resultArray[lineNum] instead of info to see if the program was able to retrieve the line and store it to the array.
Remove the initialization of String[] resultArrayOne and after fileStrm.close(), use resultArrayOne = resultArray.clone() to copy the values of resultArray to resultArrayOne. Copying an array by assignment (array1 = array2) could have side-effects you do not want in your program since you are making both arrays refer to the same object. Check this related question here
Also, why not use resultArrayOne directly when storing the lines?

How to read a file with a number on each line 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.

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.

unable to compare string read from file with java string

I am reading a file in java which has .lab extension which is basically a text file with utf characters and has content as follows:
0.100904 125 SIL
0.392625 125 तुझ्_beg
0.622405 125 या_end
0.623404 125 SIL
0.946096 125 ले_beg
1.120000 125 मळ्_mid
1.362698 125 या_end
1.363697 125 SIL
but in program when i compare as follows:
arr[2].equals("SIL")
it doesn't work.
entire java code is as follows:
public class SyllableCount
{
static final File labDir = new File("/media/sda6/tts/programs/MyWork/silence_handling/labs_4");
static final HashMap<String, ArrayList<Float>> terminalSyllMap = new HashMap<String, ArrayList<Float>> ();
public void accessFilesForFolder(final File labDir)
{
System.out.println("in method");
for (final File labFile : labDir.listFiles())
{
if (labFile.isDirectory())
{
accessFilesForFolder(labFile); //for recursive operation
} else
{
System.out.println(labFile.getName());
BufferedReader br = null;
String[] syllable = new String[100];//just an example-you have to initialize it big enough to hold all lines
float[] timeFrame = new float [100];
String sCurrentLine;
try
{
//br = new BufferedReader(new FileReader(labFile));
br = new BufferedReader(new InputStreamReader(new FileInputStream(labFile), "UTF8"));
int lineNo=0;
while ((sCurrentLine = br.readLine()) != null)
{
String[] arr = sCurrentLine.split(" ");
//for the first line it'll print
if(arr[0].equalsIgnoreCase("#"))
{
lineNo++;
continue;
}
//entering them into separate arrays
timeFrame[lineNo] = Float.parseFloat(arr[0]);
syllable[lineNo] = arr[2];
lineNo++;
}
br.close();
populateMaps(timeFrame, syllable, lineNo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(terminalSyllMap);
}
public void populateMaps(float[] timeFrame,String[] syllable, int lineNo) throws Exception
{
String syllval;
float duration;
ArrayList<Float> timeframeArray;
for(int i=0; i<lineNo-1; i++)
{
//System.out.println(syllable[i+1]);
if (syllable[i+1].equals("SIL"))
{
syllval = syllable[i];
duration = timeFrame[i+1] - timeFrame[i];
if(terminalSyllMap.containsKey(syllval))
{
timeframeArray = terminalSyllMap.get(syllval);
}
else
{
timeframeArray = new ArrayList<Float>();
}
timeframeArray.add(duration);
terminalSyllMap.put(syllval, timeframeArray);
}
}
}
public static void main(String[] args)
{
//
SyllableCount run = new SyllableCount();
run.accessFilesForFolder(labDir);
}
}
any help would be highly appreciated.
Try with:
final String[] arr = sCurrentLine.split("\\s+");

How to pass parameter to data provider in testng from csv file

Am reading data from csv file , i have test for which this data will be the input .
i want it to run as tescase for every set of value. for that am using data provider
The problem is , it is taking only the last set row of data , please help me in debugging the code
For eg : if my csv has following data
name1 id1 text1
name2 id2 text2
name3 id3 text3
it taking only last row name3 id3 text3 and running the test only once not three times.
#DataProvider(name = "test")
public Object[][] provider( ) throws InterruptedException
{
Object[][] returnObject ;
String[] checkpoint = ReadfromCSV();
count = count + 1;
returnObject = new Object[][]{checkpoint };
return returnObject;
}
#Test(description = "Test", groups = "test" , dataProvider = "test")
public void compare(String val1,String val2,String val3,String val4,String val5,String val6,String val7,String val8,String val9,String val10,String val11 ) {
System.out.println("1:" + val1);
System.out.println("4:" + val2);
System.out.println("5:" + val3);
}
#SuppressWarnings("null")
public String[] ReadfromCSV() throws InterruptedException {
String[] data= null;
String csvFile = "F:/sample1.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(cvsSplitBy);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return data;
}
You should read entire file in data provider and return iterator of test cases. Here is some pseudocode for data provider. Notice that I used List<String []> to store test cases instead of Object[][]. This allows you do define test cases dynamically.
#DataProvider(name = "test")
public Iterator<Object []> provider( ) throws InterruptedException
{
List<Object []> testCases = new ArrayList<>();
String[] data= null;
//this loop is pseudo code
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(cvsSplitBy);
testCases.add(data);
}
return testCases.iterator();
}
public String[][] ReadfromCSV() throws InterruptedException {
int count =0;
String[] data= null;
String returnObj[][] = null;
//System.out.println(System.getProperty("user.dir"));
String csvFile = System.getProperty("user.dir")+ "/src/test/resources/testdata.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<String> content = new ArrayList<String>();
try {
//this loop is pseudo code
br = new BufferedReader(new FileReader(csvFile));
int datalength = 0;
int listsize =0;;
while ((line = br.readLine()) != null) {
// use comma as separator
content.add(line);
}
System.out.println(content);
listsize = content.size();
datalength = content.get(0).split(cvsSplitBy).length;
returnObj = new String[listsize][datalength];
for (int i = 0; i<listsize; i++) {
data = content.get(i).split(cvsSplitBy);
for (int j=0; j< datalength ; j++) {
returnObj[i][j] = data[j];
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return returnObj;
}}

Categories

Resources