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+");
Related
I have a text file (.txt) and I'm stuck here.
I user a BufferReader to read all file and save in a ArrayList then put the ArrayList into a String to remove the , [ ]
Now I need to find the word of the scanner ex: (1001) in the ArrayList that the user want, and print the line of this word and the 4 lines after that. After that, edit this 4 lines and save the ArrayList to a file.
Or have something more simple without using ArrayLists?
Thank you.
System.out.println("Digite o ID ou 1 para sair: ");
Scanner sOPFicheiro = new Scanner(System.in);
opFicheiro = sOPFicheiro.nextInt();
if (opFicheiro == 1){
System.out.println("A voltar ao menu anterior...");
Thread.sleep(1000);
editarFicheiro();
} else {
//Envia para um ArrayList o ficheiro Formandos
ArrayList<String> textoFormandos = new ArrayList<String>();
BufferedReader ler = new BufferedReader(new FileReader(FichFormandos));
String linha;
while ((linha = ler.readLine()) != null) {
textoFormandos.add(linha + "\n");
}
ler.close();
//Remove , [ ] do ArrayList para enviar para o ficheiro
String textoFormandos2 = Arrays.toString(textoFormandos.toArray()).replace("[", "").replace("]", "").replace(",", "");
}
File:
Txt File
save the ArrayList to a file
Your code lucks a mean to write data into the file.
Also invoking close() without a try/catch is a bad practice because it'll lead to resource leaks in case of exceptions.
For this task, you don't need a list, after the match with the given id is found you can write these lines to a file.
To execute this code file "test.txt" must reside under the project folder, file "result.txt" will be created automatically.
public static void main(String[] args) {
try {
readFile(Path.of("test.txt"), Path.of("result.txt"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void readFile(Path target, Path result) throws InterruptedException {
Scanner sOPFicheiro = new Scanner(System.in);
int opFicheiro = sOPFicheiro.nextInt();
if (opFicheiro == 1) {
System.out.println("A voltar ao menu anterior...");
Thread.sleep(1000);
editarFicheiro();
} else {
try (BufferedReader ler = new BufferedReader(new FileReader(target.toFile()));
BufferedWriter br = new BufferedWriter(new FileWriter(result.toFile()))) {
boolean matchIsFound = false;
String linha;
while ((linha = ler.readLine()) != null && !matchIsFound) {
if (linha.contains(String.valueOf(opFicheiro))) {
for (int i = 0; i < 5; i++) {
br.write(linha);
if (i != 4) {
br.newLine();
linha = ler.readLine();
}
}
matchIsFound = true;
}
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
user input - 1001
Initial contents of the "test.txt" file:
ID: 999
Name: ________________
Data of birth: _______
NIF: _________________
Telephone: ___________
Fim ID: 999
ID: 1001
Name: Cesar Rodrige da Silva Guimaraes
Data of birth: 16/03/2003
NIF: 1111111111
Telephone: 931111111111
Fim ID: 1001
Contents of the "result.txt" file after executing the code:
ID: 1001
Name: Cesar Rodrige da Silva Guimaraes
Data of birth: 16/03/2003
NIF: 1111111111
Telephone: 931111111111
UPDATE
public static void main(String[] args) {
try {
updateUserData(Path.of("test.txt"), Path.of("temp.txt"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void updateUserData(Path original, Path temp) throws InterruptedException {
Scanner scanner = new Scanner(System.in);
int id = scanner.nextInt();
if (id == 1) {
System.out.println("A voltar ao menu anterior...");
Thread.sleep(1000);
editarFicheiro();
return;
}
String userData = readUserData(temp, id);
String originalContentWithReplacement = readAndReplace(original, userData, id);
writeData(original, originalContentWithReplacement);
}
reading user-data for the given id from the temp file
public static String readUserData(Path temp, int id) {
StringBuilder result = new StringBuilder();
try (var reader = new BufferedReader(new FileReader(temp.toFile()))) {
boolean matchIsFound = false;
String line;
while ((line = reader.readLine()) != null && !matchIsFound) {
if (line.contains(String.valueOf(id))) {
for (int i = 0; i < 5; i++, line = reader.readLine()) {
result.append(line).append(System.getProperty("line.separator"));
}
matchIsFound = true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString().stripTrailing();
}
reading the whole contents of the original file and replacing the data for the given id
public static String readAndReplace(Path original, String userData, int id) {
StringBuilder result = new StringBuilder();
try (var reader = new BufferedReader(new FileReader(original.toFile()))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.contains(String.valueOf(id))) {
result.append(line).append(System.getProperty("line.separator"));
continue;
}
result.append(userData).append(System.getProperty("line.separator"));
for (int i = 0; i < 5; i++) {
line = reader.readLine();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString().stripTrailing();
}
replacing the previous data
public static void writeData(Path original, String content) {
try (var writer = new BufferedWriter(new FileWriter(original.toFile()))) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
Instead of using an ArrayList use a StringBuilder :
StringBuilder textoFormandos = new StringBuilder();
while ...
textoFormandos.append(linha + "\n");
...
String textoFormandos2 = textoFormandos.toString();
This way you won't need to remove anything. For the rest you need to clear the requirements.
How can I sort a cvs file by one field in Java?
For example I want to sort it by the third field
I have a cvs file that looks like this:
1951,Jones,5
1984,Smith,7
...
I tried using Scanner as such, with a delimiter but I couldn't figure out how to go on:
public static void main(String[] args)
{
//String data = args[0];
Scanner s = null;
String delim = ";";
try
{
s = new Scanner(new BufferedReader (new FileReader("test.csv")));
List<Integer> three = new ArrayList<Integer>();
while(s.hasNext())
{
System.out.println(s.next());
s.useDelimiter(delim);
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
finally
{
if(s != null)
{
s.close();
}
}
}
Thank you!
public static void main(String[] args)
{
final String DELIM = ";";
final int COLUMN_TO_SORT = 2; //First column = 0; Third column = 2.
List<List<String>> records = new ArrayList<>();
try (Scanner scanner = new Scanner(new File("test.csv"))) {
while (scanner.hasNextLine()) {
records.add(getRecordFromLine(scanner.nextLine(), DELIM));
}
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
Collections.sort(records, new Comparator<List<String>>(){
#Override
public int compare(List<String> row1, List<String> row2){
if(row1.size() > COLUMN_TO_SORT && row2.size() > COLUMN_TO_SORT)
return row1.get(COLUMN_TO_SORT).compareTo(row2.get(COLUMN_TO_SORT));
return 0;
}
});
for (Iterator<List<String>> iterator = records.iterator(); iterator.hasNext(); ) {
System.out.println(iterator.next());
}
}
private static List<String> getRecordFromLine(String row, String delimiter) {
List<String> values = new ArrayList<String>();
try (Scanner rowScanner = new Scanner(row)) {
rowScanner.useDelimiter(delimiter);
while (rowScanner.hasNext()) {
values.add(rowScanner.next());
}
}
return values;
}
** Note that the example file is separated by comma, but in the code you use semicolon as the delimiter.
I am trying to develop a basic java program to compare two huge text files and print non matching records .i.e. similar to minus function in SQL. but I am not getting the expected results because all the records are getting printed even though both files are same. Also suggest me whether this approach is performance efficient for comparing two huge text files.
import java.io.*;
public class CompareTwoFiles {
static int count1 = 0 ;
static int count2 = 0 ;
static String arrayLines1[] = new String[countLines("\\Files_Comparison\\File1.txt")];
static String arrayLines2[] = new String[countLines("\\Files_Comparison\\File2.txt")];
public static void main(String args[]){
findDifference("\\Files_Comparison\\File1.txt","\\Files_Comparison\\File2.txt");
displayRecords();
}
public static int countLines(String File){
int lineCount = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(File));
while ((br.readLine()) != null) {
lineCount++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return lineCount;
}
public static void findDifference(String File1, String File2){
String contents1 = null;
String contents2 = null;
try
{
FileReader file1 = new FileReader(File1);
FileReader file2 = new FileReader(File2);
BufferedReader buf1 = new BufferedReader(file1);
BufferedReader buf2 = new BufferedReader(file2);
while ((contents1 = buf1.readLine()) != null)
{
arrayLines1[count1] = contents1 ;
count1++;
}
while ((contents2 = buf2.readLine()) != null)
{
arrayLines2[count2] = contents2 ;
count2++;
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void displayRecords() {
for (int i = 0 ; i < arrayLines1.length ; i++) {
String a = arrayLines1[i];
for (int j = 0; j < arrayLines2.length; j++){
String b = arrayLines2[j];
boolean result = a.contains(b);
if(result == false){
System.out.println(a);
}
}
}
}
}
Based upon your explanation you do not need embedded loops
consider
public static void displayRecords() {
for (int i = 0 ; i < arrayLines1.length && i < arrayLines2.length; i++)
{
String a = arrayLines1[i];
String b = arrayLines2[i];
if(!a.contains(b){
System.out.println(a);
}
}
For the performance wise, you should try to match the size of the files. If the sizes(in bytes) are exactly the same, you might not need to compare them.
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;
}}
I have create the following program and I am little stuck here.
Here is the code:
class ProductNameQuan{
public static void main(String[] args)
{
String fileName = "stockhouse.txt";
StringTokenizer line;
String ProdName;
String quantity;
try {
BufferedReader in = new BufferedReader(new FileReader(fileName));
line = in.readLine();
while (line != null) {
ProdName = line.nextToken();
quantity = line.nextToken();
System.out.println(line);
line = in.readLine();
}
in.close();
} catch (IOException iox)
{
System.out.println("Problem reading " + fileName);
}
}
}
I am trying to find the way to read from the file the first 10 information's through the array (not arraylist)ProdName and the quantity." plus that I stack in the in.readLine(); propably is not compatible with the StringTokenizer.
Now the other problem is that I need the quantity to be an integer instead of string.
The file includes something like that:
Ball 32
tennis 322
fireball 54
..
.
.
.
.
Any ideas?
I would place this in a helper function, maybe called parseString
class ProductNameQuan {
public static void main(String[] args)
{
...
try {
BufferedReader in = ...
line = in.readLine();
while (line != null) {
ProductNameQuan.parseString(line);
}
}
...
}
public static void parseString(String someString)
{
StringTokenizer st = new StringTokenizer(someString);
while (st.hasMoreTokens()) {
String token = line.nextToken();
try {
int quantity = Integer.parseInt(token)
// process number
} catch(NumberFormatException ex) {
// process string token
}
}
}