Search an array with variable column sizes java - java

I want to display some of the content of the .txt file on the screen after copying it into a new file. The content of the text file is not exactly the same structure throughout.
When i did this
if (m[11].equals("Channel") && m[12].equals("ID")){ System.out.println("Wavelenght ID = " + m[9]);
I got an error array out of bounds.
TESTSTEP: DEBUG * Fpga Config ECFG *: EED 3 : Channel ID
If this line was found i want it to display Wavelenght ID = 3
String p = path.replace("\\", "\\\\");
File file = new File(p);
File[] files = file.listFiles();
BufferedReader inputStream = null;
PrintWriter outputStreamI = null;
PrintWriter outputStreamO = null;
try {
String l,c;
for (int i=0; i<files.length; i++){
inputStream = new BufferedReader(new FileReader(files[i].getAbsolutePath()));
outputStreamI = new PrintWriter(new FileWriter("S:\\WRED_IBP\\" + files[i].getName().replaceFirst("[.][^.]+$", "")+ "Ingress.txt"));
outputStreamO = new PrintWriter(new FileWriter("S:\\WRED_IBP\\" +files[i].getName().replaceFirst("[.][^.]+$", "")+ "Egress.txt"));
while ((l = inputStream.readLine())!= null) {
String[] m=l.split(" ");
for(int d=0; d<m.length; d++){
c=m[d];
if (c.equalsIgnoreCase("ied_wred") ){outputStreamI.println(l); if (outputStreamI.checkError()){System.err.println("Error in output stream");}} //|| c.equalsIgnoreCase("WARNING") || c.equals("ERROR")
else if (c.equalsIgnoreCase("eed_brc_ibp")){outputStreamO.println(l); if (outputStreamO.checkError()){System.err.println("Error in output stream");}} // || c.equalsIgnoreCase("WARNING") || c.equals("ERROR")
}
}
}
} catch(IOException e){
System.err.println("Caught IOException: " + e.getMessage());
}//wait(10);
finally {
if (inputStream != null) {
try{ inputStream.close();} catch (IOException e) {e.printStackTrace();}}
if (outputStreamI != null) {outputStreamI.close();}
if (outputStreamO != null) {outputStreamO.close();}
}
}

You can use:
if (m.length > 12 && m[11].equals("Channel") && m[12].equals("ID")){
System.out.println("Wavelenght ID = " + m[9]);
}
So index out of bound won't happen here.
Make sure you put these lines before the for loop.

TESTSTEP: DEBUG * Fpga Config ECFG *: EED 3 : Channel ID
I'm assuming this is the text in the file. When you read this, you are trying to split it based on spaces. What you should be doing is split it based on :.

Related

Writer dont writing in file but only create it

Im working on converter. I load file, start reading date from it and creating directories by year, month and day(+ another one dir) in witch ends are those converted text files. Everything is fine while creating those directories but in text files is nothing or only chunk of it.
public static void convertFile(File fileToConvert, File whereToSave, long shift) {
BufferedReader reader = null;
BufferedWriter writer = null;
String oldDate = "";
String newDate = "";
boolean boolDate = true;
try {
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
boolean block = true;
String line = "";
int lineCounter = 0;
while ((line = reader.readLine()) != null) {
if (lineCounter==0) {
block = true;
} else {
block = false;
}
line = line.replaceAll("[^0-9-,:+NaN.]", "");
String[] data = line.split(",");
if (block) {
data[0] = data[0].substring(0, 10) + " " + data[0].substring(10);
data[0] = SimulatorForRealData.timeShift(data[0], shift);
// ====================================================================================
newDate = data[0].substring(0, 4) + " " + data[0].substring(5, 7) + " "
+ data[0].substring(8, 10);
String savingIn = SimulatorForRealData.createDirs(whereToSave.toString(),
data[0].substring(0, 4), data[0].substring(5, 7), data[0].substring(8, 10));
File f = new File(savingIn + "\\" + FILE_NAME + ".log");
if (!newDate.equals(oldDate) && boolDate == false) {
writer.close();
boolDate = true;
} else {
oldDate = newDate;
boolDate = false;
}
writer = new BufferedWriter(new FileWriter(f));
// =====================================================================================
writer.write("<in date=\"" + data[0].substring(0, 10) + "T" + data[0].substring(11)
+ "\" t=\"1\" >\n");
writer.write(data[0] + "\n");
writer.write(0 + " " + 0 + " " + 0 + "\n");
for (int x = 0; x <= 10; x++) {
writer.write("NaN" + " ");
}
writer.write("\n");
for (String s : data) {
if (s.equals(data[0])) {
continue;
}
writer.write(s + ";");
}
writer.write("\n");
} else {
for (String s : data) {
writer.write(s + ";");
}
writer.write("\n");
}
lineCounter++;
if (lineCounter == 118) {
lineCounter = 0;
writer.write("</in>\n\n");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is method where i perform it. Can someone help me. I tried different "writers" and nothing. I have suspicious that it will be problem in closing file but i dont know for sure.
I think you should close every writer you created, not only last one.
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
...
writer = new BufferedWriter(new FileWriter(f));
while ((line = reader.readLine()) != null) {
....
}
writer.close();
}
writer flushes all changes on disk only when buffer is overflowed or it is closed.
I see two main problems:
You create a file every time you read a line. You should put it outside the loop (or loops, if you want only one file)
Always data is written with the same filename. It should have different filenames if you make a file for every file read.

CSV writing data beside each other

I am writing to CSV file the BLE scanned results. What I am doing currently is writing all the data one below another.
The data consists of device name, rssi and mac address. For example, the CSV file looks like this -
DeviceA -85 DS:DA:AB:2B:B4:AE
DeviceB -100 2C:18:0B:2B:96:9E
DeviceA -85 DS:DA:AB:2B:B4:AE
My requireemnt is to write like this -
DeviceA -85 DS:DA:AB:2B:B4:AE DeviceB -100 2C:18:0B:2B:96:9E
DeviceA -85 DS:DA:AB:2B:B4:AE
After the last column of device A, I need to start with new column of device B instead of writing below device A.
Also for Device C, I want to write it beside Device C...And so on. Here is my code for writing to CSV.
public final String DATA_SEPARATOR = ",";
public final String LINE_SEPARATOR = System
.getProperty("line.separator");
try {
fileName = "test.csv";
path = Environment.getExternalStorageDirectory()
+ File.separator + "Documents";
path += File.separatorChar + "SampleApp";
File file = new File(path, fileName);
new File(path).mkdirs();
file.createNewFile();
fileStream = new OutputStreamWriter(new FileOutputStream(file));
fileStream.write("sep= " + DATA_SEPARATOR + LINE_SEPARATOR);
} catch (IOException e) {
e.printStackTrace();
fileStream = null;
}
private void writeElements(Object... elements) throws IOException {
if (fileStream != null) {
for (Object o : elements) {
fileStream.write(o.toString());
fileStream.write(DATA_SEPARATOR);
}
fileStream.write(LINE_SEPARATOR);
}
}
writeElements(btDeviceName, btRSSIValue, btMacId) is called from bluetoothScan() method every now and then.
How can I achieve writing beside?
Just put 2 on the same line before writing a LINE_SEPARATOR. Change what's in your writeElements to something like this:
private void writeElements(Object... elements) throws IOException {
if (fileStream != null) {
for (int index = 1; index < elements.length + 1; index++) {
String address = elements[index - 1].toString();
fileStream.write(address);
if(index % 2 == 0) fileStream.write(LINE_SEPARATOR);
else fileStream.write(DATA_SEPARATOR);
}
}
}
Testing:
Object[] elements = new Object[4];
elements[0] = "here";
elements[1] = "are";
elements[2] = "some";
elements[3] = "words";
writeElements(elements);
When opening the file:
here,are
some,words

How to write number using fileoutputstream

I'm new to java , i need to define counter then write the result in a file
int counter=0;
int resultstweets=0;
fos = new FileOutputStream(new File(
prop.getProperty("PATH_TO_OUTPUT_FILE")));
BufferedReader br = new BufferedReader(new FileReader("path/of/file"));
while ((tweetJson = br.readLine()) != null) {
String result = drpc.execute(TOPOLOGY_NAME, tweetJson);
Status s = null;
try {
s = DataObjectFactory.createStatus(tweetJson);
result = s.getId() + "\t" + s.getText() + "\t" + result;
// this is my counter
resultstweets+=counter;
} catch (TwitterException e) {
LOG.error(e.toString());
}
fos.write(result.getBytes());
fos.write(newLine);
}
fos.write(newLine);
fos.write("Finish: ".getBytes());
fos.write("resultstweets".getBytes());
fos.write(newLine);
// here i write it in the file
fos.write(resultstweets);
but what i got at the end of file
Finish: resultstweets
**\001**459202139258
This method java.io.FileOutputStream.write(byte[] b) you're using in your last line gets a byte array as parameter.
So you should first convert your integer to string and then call getBytes on that:
fos.write(String.valueOf(resultstweets).getBytes());
You can find a proper example of using this method here.

BufferedReader - count lines containing a string

I am using a .txt file that contains: "Hello world\nHow are you doing this day?" I want to count whether a line contains a string or not, as well as the total number of lines. I use:
File file = new File(file_Path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i=0;
int j=0;
while ((line = br.readLine()) != null) {
j++;
if (line.contains("o")) { //<----------
i++;
}
}
System.out.print("Lines containing the string: " + i + " of total lines " + j-1);
As I run and test line.contains("o"), it prints 2 lines containing "o", which is correct as well as 2 total lines. As I run line.contains("world"), it prints 0 lines which is wrong but gives 2 lines total. But what do I do wrong?
I tested it with a StringReader,
String str = "Hello world\nHow are you doing this day?";
StringReader sr = new StringReader(str);
try {
BufferedReader br = new BufferedReader(sr);
String line;
int i = 0;
int j = 0;
while ((line = br.readLine()) != null) {
j++;
if (line.contains("world")) { // <----------
i++;
}
}
System.out
.println("Lines containing the string: " + i
+ " of total lines " + j);
} catch (Exception e) {
e.printStackTrace();
}
Your file contents must not be what you think because I get
Lines containing the string: 1 of total lines 2
As the others answers and comments, I also think you may not be reading the file you think you are... (Relax it happens to everyone from time to time)
But, also it could be the encoder of the file or the version of the jdk you have, maybe if you could answer:
What did you use to create the file?
What OS you are running
this?
What JDK are you using?
It could clarify what may have happened
Just for you to know, I ran the same code you have using jdk8 and worked fine for me.
As follows the test I did:
1) I put your code in a function:
int countLines(String filename, String wording) {
File file = new File(filename);
String line;
int rowsWithWord = 0;
int totalRows = 0;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
totalRows++;
if (line.contains(wording)) {
rowsWithWord++;
}
}
} catch (IOException e) {
System.out.println("Error Counting: " + e.getMessage());
}
System.out.println(String.format("Found %s rows in %s total rows", rowsWithWord, totalRows));
return rowsWithWord;
}
2) and ran the following unit test
#Test
public void testFile() {
try (FileWriter fileWriter = new FileWriter(new File("C:\\TEMP\\DELETE\\Hello.txt"));
BufferedWriter writer = new BufferedWriter(fileWriter)) {
writer.write("Hello world\nHow are you doing this day?");
} catch (IOException e) {
System.out.println("Error writing... " + e);
}
int countO = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "o");
Assert.assertEquals("It did not find 2 lines with the letters = o", 2, countO);
int countWorld = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "world");
Assert.assertEquals("It did not find 1 line with the word = world", 1, countWorld);
}
And I got the expected result:
Found 2 rows in 2 total rows
Found 1 rows in 2 total rows

Directory not being recognized

So I have a method that reads all the files in a folder and creates new classes in a List with the variables read from the files. For some reason it doesn't ever get past the if(mainDir.isDirectory()){ part, even though the paths are correct and I double checked the folders were there.
public static void loadIntoClass(String dir, int temp){
try {
File mainDir = new File(dir);
if(mainDir.isDirectory()){ //Checks if the dir is a folder and not a file
String[] fileNames = mainDir.list(); //Grabs a list of all the filenames in the dir
for(int x = 0; x > fileNames.length; x++){ //loops through all the files
File currFile = new File(dir + fileNames[x]); //Creates the object we will be gathering information from
if(currFile.isFile()){ //Checks to make sure the file is a file and not a folder
BufferedReader br = new BufferedReader(new FileReader(currFile));
String line = br.readLine();
int currLoop = 1;
boolean collides = false;
while(line != null){ //Will keep checking files until it reaches a blank line
currLoop ++; //Keeps track of how many times it loops
test = line.split("="); //Splits up the variable from the declaration
String toString = test[0].trim(); //Trims off any extra blank spaces on either side
System.out.println("Reading: " + toString + " on line " + currLoop); //For debugging
String toString2 = test[1].trim(); //Trims the second string
parse[currLoop] = Integer.parseInt(toString2); //Turns the string into an integer then puts it into the array
if(toString.equalsIgnoreCase("Collides")){
if(toString2.equalsIgnoreCase("true")){
collides = true;
}
}
if(toString.equalsIgnoreCase("Image Path")){
//path = toString2;
}
line = br.readLine();
}
if(temp == 1){
types.add(new Type(parse[1], parse[2], parse[3], parse[4], parse[5], parse[6], parse[7]));
}
if(temp == 2){
tiles.add(new Tiles(parse[1], collides, null));
}
if(temp == 3){
abilities.add(new Abilities(parse[1], parse[2], parse[3], parse[4]));
}
br.close();
}
}
}
} catch(Exception e) {
System.err.println("ERROR: " + e);
}
}
After that if I change it some other path like "C:/test" it works only to freeze at the for loop. Here's the declaration:
loadIntoClass("C:/Program Files(x86)/GameNameHere/config/enemies", 1);
The methods isDirectory() and isFile() doe not work if the underlying FS-Objects do not exist.
There are multiple possible issues, which you are not taking into consideration...
Your not checking to see if the dir exists
Your not making sure to close your files in case of an read error (or other associated error)
You making life tough for yourself using File#list, instead use File#listFiles which will return an array of File
Make better use of exceptions...
For example...
public static void loadIntoClass(String dir, int temp) throws IOException {
File mainDir = new File(dir);
if(mainDir.exists) { // Check to see if the abstract path actually exists
if (mainDir.isDirectory()){ //Checks if the dir is a folder and not a file
File[] fileNames = mainDir.listFiles(); //Grabs a list of all the filenames in the dir
//String[] fileNames = mainDir.list(); //Grabs a list of all the filenames in the dir
if (fileNames != null && fileNames.length > 0) {
//for(int x = 0; x > fileNames.length; x++){ //loops through all the files
for(File currFile : fileNames){ //loops through all the files
//File currFile = new File(dir + fileNames[x]); //Creates the object we will be gathering information from
if(currFile.isFile()){ //Checks to make sure the file is a file and not a folder
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(currFile));
String line = null;
int currLoop = 1;
boolean collides = false;
while((line = br.readLine()) != null){ //Will keep checking files until it reaches a blank line
//...//
}
//...//
// Make sure you make all best attempts to close the reader...
} finally {
try {
br.close();
} catch (Exception exp) {
}
}
}
}
} else {
// You may not care, but...
throw new IOException(dir + " does not contain any files");
}
} else {
throw new IOException(dir + " is not a directory");
}
} else {
throw new IOException(dir + " does not exist");
}
}

Categories

Resources