parse text file name with jsp - java

I need to get the name of the file which actually begins with something like 45-something.log. I could grab 45, but not the rest since something consists of random numbers. Moreover, such this file is already on server and I need to look for it beforehand.
I already tried something like following:
<%
String line ="";
String file = "/tmp/smsrouter/" + pageContext.getAttribute("cid");
BufferedReader br = new BufferedReader(new FileReader(file));
int count = 0;
int lineNumber = 0;
while((line=br.readLine())!=null)
{
String[] parts = line.split("\\,");
lineNumber++;
if(parts[3].equals("0") && count < lineNumber)
{
count++;
}
}
count = (count/lineNumber)*100;
br.close();
%>
obviously, it won't get any result as expected. What should I do then?

Why not iterator /tmp/smsrouter/ dir and match file name you want?
File[] files = new File("/tmp/smsrouter/").listFiles();
for (File file : files) {
if (file.isDirectory()||!file.getName().startsWith("45-")) {
continue;
} else {
BufferedReader br = new BufferedReader(new FileReader(file));
int count = 0;
int lineNumber = 0;
while((line=br.readLine())!=null)
{
String[] parts = line.split("\\,");
lineNumber++;
if(parts[3].equals("0") && count < lineNumber)
{
count++;
}
}
count = (count/lineNumber)*100;
br.close();
}
}
probably you want extract the count logic to another method. Hope this help.
This is not suggested in real production system , as the invoking maybe very long that request timeout maybe raised.

Related

Writing an ArrayList to BufferedWriter using charArray()

The code snippet splits a CSV file into multiple CSV files and writes the first column content to the child CSV files. What I observed with this code is the column header "UNIQUE ID" is only appearing in FIRST CSV file. The following CSV files only contains data without the header. In order to get header to all files I thought of using an ArrayList so that I can put the header at the first index of ArrayList and rest of data afterwards. But I failed miserably.
I require suggestion or help for how to modify the code so that all the child files should have an additional UNIQUE IDENTIFIER row along as the first row with the column data. I am pasting the code which I tried and didn't work. Child csv should look like this This is what I am getting
public static void myFunction(int lines, int files) throws FileNotFoundException, IOException {
String inputfile = "C:/Users/Downloads/CONSOLIDATED.csv";
BufferedReader br = new BufferedReader(new FileReader(inputfile));
String strLine = null;
for (int i = 1; i <= files; i++) {
FileWriter fstream1 = new FileWriter("C:/Users/Downloads/FileNumber_" + i + ".csv");
BufferedWriter out = new BufferedWriter(fstream1);
for (int j = 0; j < lines; j++) {
strLine = br.readLine();
if (strLine != null) {
String strar[] = strLine.split(",");
ArrayList<String> al=new ArrayList<String>();
al.add(0,"Unique Identifier");
al.add(1,strar[0]);
char c[] = al.toString().toCharArray();
out.write(c);
out.newLine();
}
}
out.close();
}
br.close();
}
Your problem is that you are not keeping the headers out of the loops. Try something reading the first line before the main loop and store the headers in the List. then, every time you create a new file, before starting the inner loop, write the header in the first line of each file.
public static void myFunction(int lines, int files) throws FileNotFoundException, IOException {
String inputfile = "C:/Users/Downloads/CONSOLIDATED.csv";
BufferedReader br = new BufferedReader(new FileReader(inputfile));
String strLine = br.readLine(); //here you have the headers
String[] headers=strLine.split(",");
for (int i = 1; i <= files; i++) {
FileWriter fstream1 = new FileWriter("C:/Users/Downloads/FileNumber_" + i + ".csv");
BufferedWriter out = new BufferedWriter(fstream1);
out.write(headers[0]);
for (int j = 0; j < lines; j++) {
out.newLine();
strLine = br.readLine();
if (strLine != null) {
String strar[] = strLine.split(",");
out.write(strar[0]);
}
}
out.close();
}
br.close();
}

combine two methods in Java together in this Java code

I want combine the two methods Just some error in my document parser, frequencyCounter and parseFiles thsi code.
I want all of frequencyCounter should be a function that should be executed from within parseFiles, and relevant information don't worry about the file's content should be passed to doSomething so that it knows what to print.
Right now I'm just keep messing up on how to put these two methods together, please give some advices
this is my main class:
public class Yolo {
public static void frodo() throws Exception {
int n; // number of keywords
Scanner sc = new Scanner(System.in);
System.out.println("number of keywords : ");
n = sc.nextInt();
for (int j = 0; j <= n; j++) {
Scanner scan = new Scanner(System.in);
System.out.println("give the testword : ");
String testWord = scan.next();
System.out.println(testWord);
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
// System.out.println(strLine);
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code below gives you this output:
Professor frequency: 54
engineering frequency: 188
data frequency: 2
mining frequency: 2
research frequency: 9
Though this is only for doc1, you've to add a loop to iterate on all the 5 documents.
public class yolo {
public static void frodo() throws Exception {
String[] keywords = { "Professor" , "engineering" , "data" , "mining" , "research"};
for(int i=0; i< keywords.length; i++){
String testWord = keywords[i];
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hope this helps!

how to split 100 lines in a xml file which has n number of lines and add it to sub files using java

I am new to the programming please help me regarding this scenario.
I am trying to design a code for a program
I have a xml files which contains X number of lines and i need to put first 100 lines of that file to another sub file and next to another sub file and so on up to the end. naming convention should be like file1, file2,....
Input files will be of 5000, 10000 or even more lines
I need a dynamic code for this scenario using dom parser
i designed a code for a file with constant lines.
import java.io.*;
public class splitting
{
public static void main(String args[])throws Exception
{
int count = 0;
BufferedReader br = null;
FileWriter fileWriter1 = new FileWriter("C:\\senderoutput1.txt");
FileWriter fileWriter2 = new FileWriter("C:\\senderoutput2.txt");
FileWriter fileWriter3 = new FileWriter("C:\\senderoutput3.txt");
FileWriter fileWriter4 = new FileWriter("C:\\senderoutput4.txt");
try {
String currentLine;
br = new BufferedReader(new FileReader("C:\\senderinput.txt"));
while ((currentLine = br.readLine()) != null)
{
count++;
if (count <= 100)
{
fileWriter1.write(currentLine + System.getProperty("line.separator", "\r\n"));
} else if (count > 100 && count <= 200)
{
fileWriter2.write(currentLine + System.getProperty("line.separator", "\r\n"));
}else if (count > 200 && count <= 300)
{
fileWriter3.write(currentLine + System.getProperty("line.separator", "\r\n"));
}else if (count > 300 && count <= 400)
{
fileWriter4.write(currentLine + System.getProperty("line.separator", "\r\n"));
}
}
} finally
{
if (br != null)
{
br.close();
}
fileWriter1.close();
fileWriter2.close();
fileWriter3.close();
fileWriter4.close();
System.out.println("File Splitting was successful!!!");
}
}
}
this code is for the file which has 400 lines.
how to do it for n number of lines?
You can do something like this to achieve what you are trying to achieve:
BufferedReader br = null;
FileWriter fileWriter = new FileWriter("C:\\senderoutput1.txt");
try {
String currentLine = null;
br = new BufferedReader(new FileReader("C:\\senderinput.txt"));
while ((currentLine = br.readLine()) != null) {
/* Increment Counter */
++count;
/* Write Text To File */
fileWriter.write(currentLine + System.getProperty("line.separator", "\r\n"));
/* Check Split Condition */
if (count % 100 == 0) {
/* Close Already Open File */
fileWriter.close();
/* Point To New File */
fileWriter = new FileWriter("C:\\senderoutput" + (count/100 + 1) + ".txt");
}
}
/* Close Last Open File */
fileWriter.close();
} finally {
if (br != null) {
br.close();
}
System.out.println("File Splitting Completed Successfully!!!");
}
Please note that this is just to give you an idea and you can modify it as per your needs.
Beginner approach:
1) Read the next line in a loop.
2) Increment a counter & append the current line into a String.
3) Every time the counter hits a new 100 decimal value,
write out the String (which contains the collection of lines)
to a new file.
4) Clear the string.
I believe it's much better to make a description, then giving out code, especially for beginners.
Write the n lines in m no. of files (as User input) :
You should try this easiest code to achieve this dynamically.
I am using here Buffered Reader, Buffered Writer and java streams to get this :
//Code here :
String curpath = System.getProperty("user.dir");
List<String> list = null;
BufferedWriter bw1 = null;
Scanner sc = new Scanner(System.in);
System.out.println("How many lines you want per file, Please Enter");
String nfr = sc.nextLine();
int nfr1 = Integer.parseInt(nfr);
System.out.println("How many file you want, Please Enter");
String nfr2 = sc.nextLine();
int nfr3 = Integer.parseInt(nfr2);
sc.close();
int count = 1;
int i = nfr1; // no. of lines per file
int b = 0;
for (int j = 1; j <= nfr3; j++) { // nfr3 -- no. of files create
BufferedReader br = new BufferedReader(new FileReader(curpath + "//datafile.txt"));
list = br.lines().skip(b).limit(i).collect(Collectors.toList());
b = count * i; //skip the lines
File file1 = new File(curpath + "//Split_Line" + "//file" + j + ".txt" + " ");
file1.getParentFile().mkdirs();
file1.createNewFile();
bw1 = new BufferedWriter(new FileWriter(file1));
for (String record : list)
bw1.write((record + System.lineSeparator()));
br.close();
bw1.flush();
count++;
}
System.out.println("Split_line file complete");
bw1.close();
I suppose, it would be helpful to you. If you want to suggest anything to improve code. please comment

Take values from a text file and put them in a array

For now in my program i am using hard-coded values, but i want it so that the user can use any text file and get the same result.
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class a1_12177903
{
public static void main(String [] args) throws IOException
{
if (args[0] == null)
{
System.out.println("File not found");
}
else
{
File file = new File(args[0]);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
while (br.ready())
{
line += br.readLine();
}
String[] work = line.split(",");
double[] doubleArr = new double[work.length];
for (int i =0; i < doubleArr.length; i++)
{
doubleArr[i] = Double.parseDouble(work[i]);
}
double maxStartIndex=0;
double maxEndIndex=0;
double maxSum = 0;
double total = 0;
double maxStartIndexUntilNow = 0;
for (int currentIndex = 0; currentIndex < doubleArr.length; currentIndex++)
{
double eachArrayItem = doubleArr[currentIndex];
total += eachArrayItem;
if(total > maxSum)
{
maxSum = total;
maxStartIndex = maxStartIndexUntilNow;
maxEndIndex = currentIndex;
}
if (total < 0)
{
maxStartIndexUntilNow = currentIndex;
total = 0;
}
}
System.out.println("Max sum : "+ maxSum);
System.out.println("Max start index : "+ maxStartIndex);
System.out.println("Max end index : " +maxEndIndex);
}
}
}
I've fixed it so it takes in the name of the text file from the command line. if anyone has any ways to improve this, I'll happily accept any improvments.
You can do this with Java8 Streams, assuming each entry has it's own line
double[] doubleArr = Files.lines(pathToFile)
.mapToDouble(Double::valueOf)
.toArray();
If you were using this on production systems (rather than as an exercise) it would be worth while to create the Stream inside a Try with Resources block. This will make sure your input file is closed properly.
try(Stream<String> lines = Files.lines(path)){
doubleArr = stream.mapToDouble(Double::valueOf)
.toArray();
}
If you have a comma separated list, you will need to split them first and use a flatMap.
double[] doubleArr = Files.lines(pathToFile)
.flatMap(line->Stream.of(line.split(","))
.mapToDouble(Double::valueOf)
.toArray();
public static void main(String[] args) throws IOException {
String fileName = "";
File inputFile = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(inputFile));
// if input is in single line
StringTokenizer str = new StringTokenizer(br.readLine());
double[] intArr = new double[str.countTokens()];
for (int i = 0; i < str.countTokens(); i++) {
intArr[i] = Double.parseDouble(str.nextToken());
}
// if multiple lines in input file for a single case
String line = "";
ArrayList<Double> arryList = new ArrayList<>();
while ((line = br.readLine()) != null) {
// delimiter of your choice
for (String x : line.split(" ")) {
arryList.add(Double.parseDouble(x));
}
}
// convert arraylist to array or maybe process arrayList
}
This link may help: How to use BufferedReader. Then you will get a String containing the array.
Next you have several ways to analyze the string into an array.
Use JSONArray to parse it. For further information, search google for JSON.
Use the function split() to parse string to array. See below.
Code for way 2:
String line="10,20,50";//in fact you get this from file input.
String[] raw=line.split(",");
String[] arr=new String[raw.length];
for(int i=0;i<raw.length;++i)arr[i]=raw[i];
//now arr is what you want
Use streams if you are on JDK8. And please take care of design principles/patterns as well. It seems like a strategy/template design pattern can be applied here. I know, nobody here would ask you to focus on design guidelines.And also please take care of naming conventions. "File" as class name is not a good name.

Read first character on each line in a file

I have a file in this format:
0 2 4
3 2 4
3 5 2
1 8 2
My aim is to read the first line on each file and store it in a array. So at the end I should have 0,3,3,1
I thought one approach would be, read the line until we encounter a space and save that in a array...but it would keep on reading 2 and 4 after
Is there a efficient way of doing this, my cod is shown below:
openandprint()
{
int i = 0;
try (BufferedReader br = new BufferedReader(new FileReader("final.txt")))
{
String line;
while ((line = br.readLine()) != null) {
int change2Int=Integer.parseInt(line.trim());
figures [i] = change2Int;
i++;
}
}
catch (Exception expe)
{
expe.printStackTrace();
}
}
Using a Scanner would make the code considerably cleaner:
private static openandprint() throws IOException {
int i = 0;
try (Scanner s = new Scanner("final.txt"))) {
String line;
while (s.hasNextLine()) {
int change2Int = s.nextInt();
s.nextLine(); // ignore the rest of the line
figures [i] = change2Int;
i++;
}
}
}
Try
int change2Int=Integer.parseInt((line.trim()).charAt(0)-'0');
or
int change2Int=Character.getNumericValue(line.charAt(0));
with your approch you are reading the whole line and parsing it to int which will give you NumberFormatException because of the space between the digits.
BufferedReader br = ...;
String line = null;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" ");
int next = Integer.parseInt(parts[0]);
System.out.println("next: " + next);
}

Categories