Java get all class and id names from css file - java

I am trying to get all the classes and ids from a css file in arrays. the arrays should look like this:
UsedIds: {"#id1, "#id2" etc.etc.etc.}
UsedClasses: {".class1", ".class2" etc.etc.etc.}
how do i get these results without getting the stuff with "." inside the curly braces? I tried to remove every "{code inside}" segment but there are mediaqueries and stuff conflicting with it. My first attempt is below here, but i am not proud of it... It only removes the curly codes, but i'm stuck with this right now. Do you guys know a easier solution?
private void getCssClasses(String fileName) {
File cssFile = new File(fileName);
Scanner sc;
try {
sc = new Scanner(cssFile);
while (sc.hasNextLine()) {
String cssLine = sc.nextLine();
int firstCurly = 0;
int lastCurly = 0;
while (cssLine.contains("{")) {
for (int i = 0; i < cssLine.length(); i++) {
String character = "" + cssLine.charAt(i);
//System.out.println(character);
if (character.contains("{")) {
//System.out.println("IN");
firstCurly = i;
}
if (character.contains("}")) {
if(firstCurly != 0){
System.out.println("OUT");
lastCurly = i;
}
}
if (firstCurly != 0 && lastCurly != 0) {
StringBuilder sb = new StringBuilder(cssLine);
sb.delete(firstCurly, lastCurly);
cssLine = sb.toString();
System.out.println("YES");
break;
}
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

Adding a substring to omit a part of the output

Below is my code...
The code below is taking a .txt file of some radiation read outs. My job is to find the max number of counts per minute in the file within 5 counts.
I'e got it working, but I need to omit the part of the line, so I thought I could make this piece of the code:
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
and integrate it in. I keep trying several cases, and am not thinking. Any advice?
`import java.util.*;
//Import utility pack, *look at all classes in package.
import java.io.*;
//Good within directory.
public class counterRadiation {
private static String infile = "4_22_18.txt";
//Input
private static String outfile = "4_22_18_stripped.txt";
private static Scanner reader;
//Output
public static void main(String[] args) throws Exception{
//throw exception and then using a try block
try {
//Use scanner to obtain our string and input.
Scanner play = new Scanner(new File(infile));
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outfile), "utf-8"));
String lineSeparator = System.getProperty("line.separator");
play.useDelimiter(lineSeparator);
while (play.hasNext()) {
String line = play.next();
if (line.matches(dataList)) {
writer.write(line + "\r\n");
}
}
writer.close();
play.close();
try {
reader = new Scanner(new File(infile));
ArrayList<String> list = new ArrayList<String>();
while (reader.hasNextLine()) {
list.add(reader.nextLine());
}
int[] radiCount = new int[list.size()];
for (int i = 0; i < list.size();i++) {
String[] temp = list.get(i).split(",");
radiCount[i] = (Integer.parseInt(temp[2]));
}
int maxCount = 0;
for (int i = 0; i < radiCount.length; i++) {
if (radiCount[i] > maxCount) {
maxCount = radiCount[i];
}
}
for (int i = 0;i < list.size() ;i++) {
if(radiCount[i] >= maxCount - 4) {
System.out.println(list.get(i)+" "+ radiCount[i]);
}
}
}catch(FileNotFoundException e){
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
Although it is not quite clear what you want to get rid of you could use .indexOf(String str) to define the first occurrence of the sub-string you want to exclude. For example in your code:
String data = "useful bit get rid of this";
int index = data.indexOf("get rid of this");
System.out.println(data.substring(0,index) + "are cool");
//Expected result:
//"useful bits are cool"
from Java doc

want to print a data according to row in text file

I have a text file of data like this
username=Ayyappa,password=123
username=venkata,password=456
username=Bhargav,password=789
username=Rama,password=158
username=Pusarla,password=968
i want to print the data at row number 2
(My expected output is username=venkata,password=456)
Funtion written:
public class TestDataReader {
public static String getrowvalue(String FileName, int rownum) throws IOException{
FileReader fr = new FileReader(FileName);
BufferedReader br = new BufferedReader(fr);
String lineString = null;
while((lineString = br.readLine())!= null){
int counter = 1;
if(counter == rownum){
System.out.println(lineString);
counter ++;
}
}
return lineString;
}
}
i called this function in another class
TestDataReader.getrowvalue("F:\WS_Finsys_Ayyappa\Ejagruti\TestData\login.txt", 2);
but when i am calling this function it is printing all the row data but not with row data i passed in this case i passed rownum 2 to get the row data
Your mistake is here: you simply flush counter value each time in loop:
int counter = 1;
So change it to:
int counter = 1;
while((lineString = br.readLine())!= null){
if(counter == rownum){
System.out.println(lineString);
}
counter++;
}
UPD: Also, as #Lemm Ras mentioned, you have to move counter incrementation outside if statement.
Java 8 solution:
For small files:
String line32 = Files.readAllLines(Paths.get("file.txt")).get(32)
For large files:
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
line32 = lines.skip(31).findFirst().get();
}
A simple one ,Java <8 solution:
public String readLine(int line){
FileReader tempFileReader = null;
BufferedReader tempBufferedReader = null;
try { tempFileReader = new FileReader(textFile);
tempBufferedReader = new BufferedReader(tempFileReader);
} catch (Exception e) { }
String returnStr = "ERROR";
for(int i = 0; i < line - 1; i++){
try { tempBufferedReader.readLine(); } catch (Exception e) { }
}
try { returnStr = tempBufferedReader.readLine(); } catch (Exception e) { }
return returnStr;
}

Java: Counter Indentation

I am very new to java and trying to create a java app which (when ran inside a terminal) will copy what text is inside and if there is a curly { bracket then add 3 spaces, when there is a curly } bracket then remove 3 spaces. There should be a counter to indent another 3 spaces each time a { appears (see example)
Example:
File1.txt:
Hello{StackOverflow}{Users}
The output should be File2.txt:
Hello
{
StackOverflow
}
{
Users
}
What I currently get outputed to File2.txt is:
Hello
{
StackOverflow
}
{
Users
I am missing my last bracket (how do I fix this?) and don't know how to loop my indentation based on the counter. Please help
My current code:
import java.io;
import java.util.Scanner;
public class myapp {
public static void main(String[] argv) throws IOException {
File InputFile = new File(argv[0]);
Scanner FileScanner = new Scanner(InputFile);
FileWriter Writer = new FileWriter(argv[1]);
BufferedWriter OutputWriter = new BufferedWriter(Writer);
while (FileScanner.hasNextLine() == true) {
String a = FileScanner.nextLine();
try {
int indent = 0;
{
if (a.contains("{")) {
indent++;
}
for (int i = 0; i < indent; i++) {
OutputWriter.write(" ");
}
OutputWriter.write(a);
}
if (a.contains("}")) {
indent--;
}
} catch (Exception e) {
System.out.println("Error:" + e.getMessage());
}
OutputWriter.write("}");
}
}
}
p.s in Terminal (to run/test) I use the following command:
$java myapp File1.txt File2.txt
Thank you :)
Try closing OutputWriter at the end of the method via OutputWriter.close(). It will flush the stream which is likely the cause of the missing }.
As far as your indentation issue, declare and initialize the indent counter outside the loop. Otherwise, it will get reset to 0 with each iteration.
Try this one:
public static void main(String[] args) throws IOException {
File InputFile = new File(argv[0]);
Scanner FileScanner = new Scanner(InputFile);
FileWriter Writer = new FileWriter(argv[1]);
BufferedWriter OutputWriter = new BufferedWriter(Writer);
while (FileScanner.hasNextLine() == true) {
String a = FileScanner.nextLine();
String b = "";
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == '{') {
b += "\n{\n ";
} else if (a.charAt(i) == '}') {
b += "\n}\n";
} else {
b += a.charAt(i);
}
}
OutputWriter.write(b);
OutputWriter.close();
}}}
Try this it's ok I add the finally block.`
finally{
OutputWriter.close();
}

swap first and last column of a 2D array in a text file in java

Input file-
5
1 2 3 4 5
2 3 4 5 6
3 2 1 5 8
My work is i should read this input file my.txt and swap its first and last column and output it to another file comp.txt but I am getting a blank file comp.txt
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintStream;
import java.io.*;
// to swap first and last column of 2D array
public class Swap
{
private static BufferedReader in = null;
private static int row = 0;
private static int column = 0;
private static int[][] matrix = null;
public static void main(String[] args) throws Exception
{
try
{
// String filepath = args[0];
int lineNum = 0;
int row = 0;
in = new BufferedReader(new FileReader("my.txt"));
String line = null;
while ((line = in.readLine()) != null)
{
lineNum++;
if (lineNum == 1)
{
column = Integer.parseInt(line);
}
else
{
String[] tokens = line.split(",");
for (int j = 0; j < tokens.length; j++)
{
if (j == 0) matrix[row][0] = Integer.parseInt(tokens[column]);
else matrix[row][j] = Integer.parseInt(tokens[j]);
}
row++;
}
}
}
catch (Exception ex)
{
System.out.println("The code throws an exception");
System.out.println(ex.getMessage());
}
finally
{
if (in != null) in.close();
}
try
{
PrintStream output = new PrintStream(new File("comp.txt"));
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
output.println(matrix[i][j] + " ");
}
}
output.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Here is the output I am getting at console-
The code throws an exception
null
Apart from this I am getting a blank comp.txt file
After I replaced your catch block with
catch (Exception ex)
{
System.out.println("The code throws an exception");
System.out.println(ex.getMessage());
ex.printStackTrace();
}
I could tell that the error is
java.lang.NullPointerException
at test.example.code.Swap.main(Swap.java:37)
The code throws an exception
null
Where the line is
if (j == 0) matrix[row][0] = Integer.parseInt(tokens[column]);
Because you are trying to access the 5th column of tokens but it's actually a 5-length array and indices in Java and most C-based languages in general are zero-indiced aka the valid indices are from 0 to 4.
Also, I'm not entirely sure what you are trying to do with this line, so I won't fix it, but that's the error.
EDIT:
Now this is not exactly a legitimate thing to do, but I solved it as I would have done it myself, and I will explain it afterwards. If you mustn't read the code because your "mentor" would be against it, then just read the final lines of this post and solve it on your own.
// to swap first and last column of 2D array
public class Swap
{
private static BufferedReader in = null;
private static int column = 0;
private static List<int[]> matrix = null;
public static void main(String[] args) throws Exception
{
try
{
// String filepath = args[0];
in = new BufferedReader(new FileReader("my.txt"));
String line = null;
matrix = new ArrayList<int[]>(); //array length is variable length
//so using a 2D array without knowing the row size is not right
boolean isFirstLine = true;
while ((line = in.readLine()) != null)
{
if (isFirstLine)
{
column = Integer.parseInt(line); //first line determines column length
isFirstLine = false;
}
else
{
String[] tokens = line.split(" "); // there are no commas in input file so split on spaces instead
matrix.add(new int[column]);
for (int i = 0; i < tokens.length; i++)
{
matrix.get(matrix.size() - 1)[i] = Integer.parseInt(tokens[i]);
//store the lines of the currently read line in the latest added array of the list
}
}
}
}
catch (Exception ex)
{
System.out.println("The code throws an exception");
ex.printStackTrace(); //changed exception write out for better info
}
finally
{
if (in != null)
in.close();
}
// swapping the elements of first and last in each int array of list
for(int[] intLines : matrix)
{
int temp = intLines[0];
intLines[0] = intLines[intLines.length-1];
intLines[intLines.length-1] = temp;
}
BufferedWriter output = null;
try
{
output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(
"comp.txt")))); //i just prefer bufferedwriters don't mind me
output.write("" + column); //write the first line that is the array length into file
output.newLine();
for (int[] intLines : matrix) //write out each line into file
{
for (int i = 0; i < intLines.length; i++)
{
output.write("" + intLines[i]);
if (i < (intLines.length - 1))
{
output.write(" ");
}
}
output.newLine();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if (output != null)
{
try
{
output.close();
}
catch (IOException e)
{
}
}
}
}
}
So basically I changed the 2D array to a list of arrays, read in the file, fixed that you were splitting along commas instead of spaces, and actually did the swap. You don't necessarily have to take this approach, especially if that is against the rules. Don't even read the code if you mustn't.
1) Change
System.out.println("The code throws an exception");
System.out.println(ex.getMessage());
To get detailed description for cause of exception.
System.out.println("The code throws an exception");
ex.printStackTrace();
2) From code & exception message it seems like there is a NullPointerException as ur array matrix is initialized to null and not to array of matching size.
So solution to the exception is[Assuming your core logic is fine] , before assigning any values to matrix array, initialize with relevant size i.e with max rows & columns

Why isn't my array filled correctly?

I am writing code for a game in Java. Specificly I'm working on the level creation using a character array filled by characters from a .txt file. My problem is that the array is not filled as it should be and the final line remains empty. I can't work this out so any kind of help will be gladly accepted, here's the problematic block of code :
public static void main(String[] args) throws IOException{
char background[][] = new char [14][20];
try {
FileInputStream fileinput = new FileInputStream("background.txt");
int r;
for(int i=0;i<=13;i++){
for(int j=0;j<19;j++){
while((r = fileinput.read()) != -1){
char c = (char) r;
background[i][j] = c;
break;
}
}
}
fileinput.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i=0;i<=13;i++){
for(int j=0;j<=19;j++){
System.out.print(background[i][j]);
}
}
}
Also the code as a whole can be found in the following link: http://pastebin.com/HtwMpsjm
Here's the .txt file too!
You accidentally one of your conditions, i've commented on the changed line.
As someone has mentioned in the comments, you might find it beneficial to treat your loops conditions as for(int i=0;i<20;i++) rather than for(int i=0i<=19;i++) it makes the code a little more readable.
public static void main(String[] args) throws IOException{
char background[][] = new char [14][20];
try {
FileInputStream fileinput = new FileInputStream("background.txt");
int r;
for(int i=0;i<=13;i++){
for(int j=0;j<=19;j++){//<<THIS LINE WAS CHANGED
while((r = fileinput.read()) != -1){
char c = (char) r;
background[i][j] = c;
break;
}
}
}
fileinput.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i=0;i<=13;i++){
for(int j=0;j<=19;j++){
System.out.print(background[i][j]);
}
}
}
Why do we need multiple for loops here. If you want to read characters from a file you could use buffered reader and the this matrix could be created in one line of code like while((bufferedReader.read(background[i]) != -1) && (++i < 14)){ }. Also you are using a while loop to read one char and then an unconditional break statment inside is not a good practice (in my opinion). Try
public static void main(String[] args) throws IOException {
char background[][] = new char[14][20];
try {
FileReader fileReader = new FileReader("background.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int i=0;
while((bufferedReader.read(background[i]) != -1) && (++i < 14)){ } // This like created your 2D array
bufferedReader.close();
fileReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i <= 13; i++) {
for (int j = 0; j <= 19; j++) {
System.out.print(background[i][j]);
}
}
}

Categories