I wrote a simple program to read the content from text/log file to html with conditional formatting.
Below is my code.
import java.io.*;
import java.util.*;
class TextToHtmlConversion {
public void readFile(String[] args) {
for (String textfile : args) {
try{
//command line parameter
BufferedReader br = new BufferedReader(new FileReader(textfile));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
String outputfile = new String("Test Report"+dateWithoutTime+".html");
FileWriter filestream = new FileWriter(outputfile,true);
BufferedWriter out = new BufferedWriter(filestream);
out.write("<html>");
out.write("<body>");
out.write("<table width='500'>");
out.write("<tr>");
out.write("<td width='50%'>");
if(strLine.startsWith(" CustomerName is ")){
//System.out.println("value of String split Client is :"+strLine.substring(16));
out.write(strLine.substring(16));
}
out.write("</td>");
out.write("<td width='50%'>");
if(strLine.startsWith(" Logged in users are ")){
if(!strLine.substring(21).isEmpty()){
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Red'>");
out.write("</textarea>");
}else{
System.out.println("else if block:");
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Green'>");
out.write("</textarea>");
} //closing else block
//out.write("<br>");
out.write("</td>");
}
out.write("</td>");
out.write("</tr>");
out.write("</table>");
out.write("</body>");
out.write("</html>");
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TextToHtmlConversion myReader = new TextToHtmlConversion();
String fileArray[] = {"D:/JavaTesting/test.log"};
myReader.readFile(fileArray);
}
}
I was thinking to enhance my program and the confusion is of either i should use Maps or properties file to store search string. I was looking out for a approach to avoid using substring method (using index of a line). Any suggestions are truly appreciated.
From top to bottom:
Don't use wildcard imports.
Don't use the default package
restructure your readFile method in more smaller methods
Use the new Java 7 file API to read files
Try to use a try-block with a resource (your file)
I wouldn't write continuously to a file, write it in the end
Don't catch general Exception
Use a final block to close resources (or the try block mentioned before)
And in general: Don't create HTML by appending strings, this is a bad pattern for its own. But well, it seems that what you want to do.
Edit
Oh one more: Your text file contains some data right? If your data represents some entities (or objects) it would be good to create a POJO for this. I think your text file contains users (right?). Then create a class called Users and parse the text file to get a list of all users in it. Something like:
List<User> users = User.parse("your-file.txt");
Afterwards you have a nice user object and all your ugly parsing is in one central point.
Related
My code works fine however it prints the values side by side instead of under each other line by line. Like this:
iatadult,DDD,
iatfirst,AAA,BBB,CCC
I have done a diligent search on stackoverflow and none of my solution's seem to work. I know that I have to make the change while the looping is going on. However none of the examples I have seen have worked. Any further understanding or techniques to achieve my goal would be helpful. Whatever I am missing is probably very small. Please help.
String folderPath1 = "C:\\PayrollSync\\client\\client_orginal.txt";
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
if(line.contains("fooa")||line.contains("foob")){
fileContents.add(line);
}
//---------------------------------------
}
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents);
Add a Line Feed before you add to fileContents.
fileContents.add(line+"\n");
By printing the list directly as you are doing you are invoking the method toString() overridden for the list which prints the contents like this:
obj1.toString(),obj2.toString() .. , objN.toString()
in your case the obj* are of type String and the toString() override for it returns the string itself. That's why you are seeing all the strings separated by comma.
To do something different, i.e: printing each object in a separate line you should implement it yourself, and you can simply append the new line character('\n') after each string.
Possible solution in java 8:
String result = fileContents.stream().collect(Collectors.joining('\n'));
System.out.println(result);
A platform-independent way to add a new line:
fileContents.add(line + System.lineSeparator);
Below is my full answer. Thanks for your help stackoverflow. It took me all day but I have a full solution.
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
String [] names ={"iatdaily","iatrapala","iatfirst","wpolkrate","iatjohnson","iatvaleant"};
if (Stream.of(names).anyMatch(line.trim()::contains)) {
System.out.println(line);
fileContents.add(line + "\n");
}
}
System.out.println("---------------");
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}
the practice question i got says that i need to
create a java code that reads in csv file with name and height.
to read a file you must get a file name from user as string.
then you must store contents of file into two arrays one for name (string) and height(real number).
You should read the file at least twice, once to check how many students are in the file (so you know how many students you need to store) and a couple more times to actually read the file (to get the names and height).
then prompt the user for name you want height of. it should output the height for userinput.
example csv file is
chris,180
jess,161
james, 174
its not much but this is all i could come up with i have no idea how to store name and height separately and use that array to output the results. and would i need to use split somewhere in the code? i remember learning it but dont know if its used in this situation
import.java.util.*;
private class StudentNameHeight
private void main (string [] args)
{
String filename;
Scanner sc = new scanner(system.in);
System.out.println("enter file name")
filename = sc.nextline();
readFile (filename);
}
private void readFile (String filename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
try
{
fileStrm = new FileInputStream(filename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
// ?
catch (IOException e)
{
if (fileStrm != null)
{
try {fileStrm.close(); } catch (IOException e2){}
}
System.out.println("error in processing" + e.getMessage());
}
}
im new to java so, any small tip or help would be great
thanks
You code looks messy. As far as I understand from your question, you are willing to read a CSV file containing two entities, one is name and another is height and store these two entities in two different data structures. I'm teaching you a simple way to accomplish this in below code snippet.
public void processCSVFile(String filePath){
try(BufferedReader fileReader = new BufferedReader(new FileReader(new File(filePath)))){
//Create two lists to hold name and height.
List<String> nameList = new ArrayList<>();
List<Integer> heightList = new ArrayList<>();
String eachLine = "";
/*
* Read until you hit end of file.
*/
while((eachLine = fileReader.readLine()) != null){
/*
* As it is CSV file, split each line at ","
*/
String[] nameAndHeightPair = eachLine.split(",");
/*
* Add each item into respective lists.
*/
nameList.add(nameAndHeightPair[0]);
heightList.add(Integer.parseInt(nameAndHeightPair[1]));
}
/*
* If you are very specific, you can convert these
* ArrayList to arrays here.
*/
}catch(IOException e1){
e1.printStackTrace();
}
}
I have a .txt file which contains a list of stuff I want to store in an Array and use throughout my application. To achieve this I created the following class:
public class Sort {
ArrayList<String> sorted = new ArrayList<String>();
public Sort() throws IOException {
Scanner scanner = new Scanner(new FileReader("/home/scibor/coding/src/com/myapp/readThis.txt"));
while(scanner.hasNextLine()){
sorted.add(scanner.nextLine());
}
}
}
So I have a .txt file with a bunch of stuff in it, and then I create this class specifically for that case. Now when I want to access these things in the .txt file in an ArrayList in one of my other classes, I figure:
Sort sort = new Sort();
sort.sorted; //can use the arrayList like so
Instead I get a message that says UnhandledException: java.io.IOException
I've tried several variations of this using try/catch, BufferedReader with try/catch/finally and ultimately all of them have some sort of error pertaining to the Exceptions that are raised by reading in a file. What am I doing wrong here?
EDIT: As per one of the suggestions, I have tried a radically different approach as below:
public class Sort {
List<String> sorted;
public Sort(Context context){
sorted = new ArrayList<String>();
AssetManager assetManager = context.getAssets();
try {
InputStream read = assetManager.open("readThis.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(read));
while(reader.readLine() != null){
sorted.add(reader.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This seems to get me further, and is probably very close to the correct answer. When I create Sort mySortedObject = new Sort(this); there are no errors generated. When I finally access the ArrayList though, as follows:
for(String name: mySortedObject.sort){
if(name.equals("Whatever"){
//run this
}
}
}
I get a NullPointerException on the line containing the if statement. So the object was successfully created...but not quite?
EDIT: The "readThis.txt" file is located in /assets
I believe the file "/home/scibor/coding/src/com/myapp/readThis.txt" does not exist on your phone (and for a good reason). You will need to add your .txt as an asset to your project and load it using the AssetManager.open()-method
Edit:
In your edited code, your NullPointerException is caused by you calling .readLine() twice in each iteration.
Solution:
String line = null;
while(true){
line = reader.readLine();
if (line == null) break;
sorted.add(line);
}
I want to get multiple file by parsing a input file Through Java.
The Input file contains many fasta format of thousands of protein sequence and I want to generate raw format(i.e., without any comma semicolon and without any extra symbol like ">", "[", "]" etc) of each protein sequence.
A fasta sequence starts form ">" symbol followed by description of protein and then sequence of protein.
For example ► >lcl|NC_000001.10_cdsid_XP_003403591.1 [gene=LOC100652771]
[protein=hypothetical protein LOC100652771] [protein_id=XP_003403591.1] [location=join(12190..12227,12595..12721,13403..13639)]
MSESINFSHNLGQLLSPPRCVVMPGMPFPSIRSPELQKTTADLDHTLVSVPSVAESLHHPEITFLTAFCL
PSFTRSRPLPDRQLHHCLALCPSFALPAGDGVCHGPGLQGSCYKGETQESVESRVLPGPRHRH
Like above formate the input file contains 1000s of protein sequence. I have to generate thousands of raw file containing only individual protein sequence without any special symbol or gaps.
I have developed the code for it in Java but out put is : Cannot open a file followed by cannot find file.
Please help me to solve my problem.
Regards
Vijay Kumar Garg
Varanasi
Bharat (India)
The code is
/*Java code to convert FASTA format to a raw format*/
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.io.FileInputStream;
// java package for using regular expression
public class Arrayren
{
public static void main(String args[]) throws IOException
{
String a[]=new String[1000];
String b[][] =new String[1000][1000];
/*open the id file*/
try
{
File f = new File ("input.txt");
//opening the text document containing genbank ids
FileInputStream fis = new FileInputStream("input.txt");
//Reading the file contents through inputstream
BufferedInputStream bis = new BufferedInputStream(fis);
// Writing the contents to a buffered stream
DataInputStream dis = new DataInputStream(bis);
//Method for reading Java Standard data types
String inputline;
String line;
String separator = System.getProperty("line.separator");
// reads a line till next line operator is found
int i=0;
while ((inputline=dis.readLine()) != null)
{
i++;
a[i]=inputline;
a[i]=a[i].replaceAll(separator,"");
//replaces unwanted patterns like /n with space
a[i]=a[i].trim();
// trims out if any space is available
a[i]=a[i]+".txt";
//takes the file name into an array
try
// to handle run time error
/*take the sequence in to an array*/
{
BufferedReader in = new BufferedReader (new FileReader(a[i]));
String inline = null;
int j=0;
while((inline=in.readLine()) != null)
{
j++;
b[i][j]=inline;
Pattern q=Pattern.compile(">");
//Compiling the regular expression
Matcher n=q.matcher(inline);
//creates the matcher for the above pattern
if(n.find())
{
/*appending the comment line*/
b[i][j]=b[i][j].replaceAll(">gi","");
//identify the pattern and replace it with a space
b[i][j]=b[i][j].replaceAll("[a-zA-Z]","");
b[i][j]=b[i][j].replaceAll("|","");
b[i][j]=b[i][j].replaceAll("\\d{1,15}","");
b[i][j]=b[i][j].replaceAll(".","");
b[i][j]=b[i][j].replaceAll("_","");
b[i][j]=b[i][j].replaceAll("\\(","");
b[i][j]=b[i][j].replaceAll("\\)","");
}
/*printing the sequence in to a text file*/
b[i][j]=b[i][j].replaceAll(separator,"");
b[i][j]=b[i][j].trim();
// trims out if any space is available
File create = new File(inputline+"R.txt");
try
{
if(!create.exists())
{
create.createNewFile();
// creates a new file
}
else
{
System.out.println("file already exists");
}
}
catch(IOException e)
// to catch the exception and print the error if cannot open a file
{
System.err.println("cannot create a file");
}
BufferedWriter outt = new BufferedWriter(new FileWriter(inputline+"R.txt", true));
outt.write(b[i][j]);
// printing the contents to a text file
outt.close();
// closing the text file
System.out.println(b[i][j]);
}
}
catch(Exception e)
{
System.out.println("cannot open a file");
}
}
}
catch(Exception ex)
// catch the exception and prints the error if cannot find file
{
System.out.println("cannot find file ");
}
}
}
If you provide me correct it will be much easier to understand.
This code will not win prices, due to missing java expertice. For instance I would expect OutOfMemory even if it is correct.
Best would be a rewrite. Nevertheless we all began small.
Give full path to file. Also on the output the directory is probably missing from the file.
Better use BufferedReader etc. i.o. DateInputStream.
Initialize i with -1. Better use for (int i = 0; i < a.length; ++i).
Best compile the Pattern outside the loop. But remove the Matcher. You can do if (s.contains(">") as well.
. One does not need to create a new file.
Code:
const String encoding = "Windows-1252"; // Or "UTF-8" or leave away.
File f = new File("C:/input.txt");
BufferedReader dis = new BufferedReader(new InputStreamReader(
new FileInputStream(f), encoding));
...
int i= -1; // So i++ starts with 0.
while ((inputline=dis.readLine()) != null)
{
i++;
a[i]=inputline.trim();
//replaces unwanted patterns like /n with space
// Not needed a[i]=a[i].replaceAll(separator,"");
Your code contains the following two catch blocks:
catch(Exception e)
{
System.out.println("cannot open a file");
}
catch(Exception ex)
// catch the exception and prints the error if cannot find file
{
System.out.println("cannot find file ");
}
Both of these swallow the exception and print a generic "it didn't work" message, which tells you that the catch block was entered, but nothing more than that.
Exceptions often contain useful information that would help you track down where the real problem is. By ignoring them, you're making it much harder to diagnose your problem. Worse still, you're catching Exception, which is the superclass of a lot of exceptions, so these catch blocks are catching lots of different types of exceptions and ignoring them all.
The simplest way to get information out of an exception is to call its printStackTrace() method, which prints the exception type, exception message and stack trace. Add a call to this within both of these catch blocks, and that will help you see more clearly what exception is being thrown and from where.
import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();