read a text file display result in console without delimeter - java

I would like to read a csv file and print the result in command line as seperated data without , delimetire.
for ex csv file has data
PVT Ltd, computer department, 5 Employees
That needs to be displayed in command prompt as
PVT Ltd
computer department
5 Employees
right now I have code as
try{
File myFile=new File("CSV-to-ArayList.csv");
FileReader fileReader=new FileReader(myFile);
BufferedReader reader=new BufferedReader(fileReader);
String line=null;
while((line= reader.readLine())!= null){
System.out.println(line);
}
reader.close();
}catch(Exception ex){
ex.printStackTrace();
}
But this one prints result as it is like csv file
PVT Ltd, computer department, 5 Employees
please help how would I achieve the result i want.

Here are 3 options which you can read about and experiment with:
Using java.util.Scanner
Using String.split() function
Using 3rd Party libraries like OpenCSV
And here is some code for you:
http://howtodoinjava.com/2013/05/27/parse-csv-files-in-java/
It's a nice example to experiment with basic java concepts.
I hope you do use this to gain knowledge and basic how-to.

You can split the string by separator and then join with a new separator, like a space or a new line:
So instead of:
while((line= reader.readLine())!= null){
System.out.println(line);
}
You can do:
while((line= reader.readLine())!= null){
System.out.println(line.split(",").join("\n"));
}

If the only seperator should be the "," You could first read in the whole file, and then split them into an String[], which you could then easily display line by line, or do other operations with. This would be my code:
try {
File myFile = new File("est.csv");
FileReader fileReader = new FileReader(myFile);
String result;
try (BufferedReader reader = new BufferedReader(fileReader)) {
String line;
result = "";
while ((line = reader.readLine()) != null) {
result = result.concat(line);
}
}
String[] items = result.split(",\\s*");
for (String item : items) {
System.out.println(item);
}
} catch (Exception ex) {
ex.printStackTrace();
}
The "\s*" is regex for any spaces between the items.

Related

How to edit parts of a line in a text file in java

I'm trying to delete the last four characters of all the lines in a text file. Let's say I have domain.txt and the content:
123.com
student.com
tech.net
running into hundreds of lines. How do I delete the last four characters (the extensions) to remain:
123
student
tech
etc.
I hope this helps.
UPDATED
String a ="123.com";
System.out.println(a.substring(0, a.lastIndexOf(".")));
You can do as below :
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "",
newtext = "";
while((line = reader.readLine()) != null) {
line=line.substring(0, line.lastIndexOf("."))
newtext += line + "\n";
}
reader.close();
// Now write new Content
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);
writer.close();
Do not forget to use try..catch

BufferedReader() returning empty string when there are more strings in the file?

My txt file looks like this:
data;data2;data3;data4..........up till data3146
When I open the txt file in notepad I see it in the form given above.
But when I copy paste the first few lines to another place, There is a 1 line gap b/w data1 and everything else. Because of this I am getting problems while accessing the file in Java and using the data with a bufferedreader in a loop. How can I correct this? I can't remove the empty line as it is not even visible in the original file.
You can ignore the blank line(s). Something like this -
while ((line = reader.readLine()) != null) {
if(line.trim().isEmpty()) {
continue;
}
...
you can try this way:
BufferedReader reader = new BufferedReader(new FileReader(new File("your file path")));
String str = null;
while((str = reader.readLine())!=null) {
if (str.matches("[' ']+")) {
continue;
} else {
// to do
}
}
I believe that the problem is in the line endings. Basically you can skip the empty lines:
String line;
while ((line = reader.readLine()) != null) {
if ("".equals(line.trim()) {
continue;
}
// do your stuff here
}

Java - ignoring certain characters while reading a text file

I'm trying to read a simple text file that contains the following:
LOAD
Bill's Beans
1200
20
15
30
QUIT
I need to store and print the contents line by line. I am doing so using the following code:
String inputFile = "(file path here)";
try {
Scanner input = new Scanner(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String currentLine = "";
while (!currentLine.equals("QUIT}")){
currentLine = input.nextLine();
System.out.println(currentLine);
}
input.close();
However, the output is very "messy". I am trying to avoid storing all new line characters and anything else that doesn't appear in the text file. Output is:
{\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf540
{\fonttbl\f0\fmodern\fcharset0 Courier;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\deftab720
\pard\pardeftab720\ql\qnatural
\f0\fs26 \cf0 LOAD\
Bill's Beans\
1200\
20\
15\
30\
QUIT}
Any help would be greatly appreciated, thank you!
This looks like you're reading a RTF file, isn't that so, by any chance?
Otherwise, I found reading text files is most natural for me using this construct:
BufferedReader reader = new BufferedReader(
new FileReader(new File("yourfile.txt")
);
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
// do whatever with the text line
}
Because this is an RTF file, look into this for example: RTFEditorKit
If you insist on writing your own RTF reader, the correct approach would be for you to extend FilterInputStream and handle the RTF metadata in its implementation.
Just add following code into your class, then call it with path parameter. it returns all lines as List object
public List<String> readStudentsNoFromText(String path) throws IOException {
List<String> result = new ArrayList<String>();
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File(path));
// 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);
result.add(strLine.trim());
}
//Close the input stream
in.close();
return result;
}

How to read a text file into jtextarea in Java Swing

Here is my code:
try {
String textLine;
FileReader fr = new FileReader("ad.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null) {
textLine = reader.readLine();
jTextArea1.read(reader, "jTextArea1");
}
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
And my .txt file contains the following:
contig00001 length=586 numreads=4
CGGGAAATTATCcGCGCCTTCACCGCCGCCGGTTCCACCGACGAACGGATACTGCGtGaa
ggCCGCGATCCCGTCggaCGGAAAaCGCCcTGGCCCGGGAaCATACCGTTCGGGCCGCCA
AGTGTTATAGCCGGACCACTTGTCAGAACATTTCCaaTCCGAAGATGTGAGTtCGGAAGg
TAAAAGCCCGACAAGTTGCGCGgTGAATTTACCTTtACcGCACGATATGCGTCCGTATTA
AaGAAAaGTTCGAAATTATCAGTAAGGCCGACCTGAAaGCTGACCGGGAGTTCAACAAAA
TCTGCATCACCcGGgTCACGGTCGAAATTGCTGTACGCGGCGCTGAACGTAAATTCACCC
TTTcTAAGGGTGTCGCcGTCGTAAACCGTAAaCAaGCCGGTAGCGCCGCCCATCGGGCCG
CCGGTACCAACCGTCGGTGCCGTGTTTCTtGCATCATTGTCCGATCGAGCGTTCTCGTCC
GCTTGTGCAAaTCCTGCAaTAGCTAACGTGAAAACGATCAGAGCTGTTGTAAATACTCTA
TAAGCGAGATTCATCACATTCCTCcGCCGAAATAAAAAGTTAATTt
contig00002 length=554 numreads=4
TGCGCCAaCCGCGCTCTtCATAAaTGGGCACTGCTCCCGATGGCCgACTCGGGCGGTTCG
CCATGAGATCTTTGCCtACCcAGgAaCtCACcACCAAGTCTGATTGCTGTGTGTTTtCTT
CAAGTCCCTATTTCTATTCtCTTtAATGGAACCCGTAGGAAACCCGTGTAGGACGCGGGA
aCCGCACTTgAAGGGGGAGGCGCGGGGTACCGGtCCGGGAACGTACGGGTACCGGCGGGG
gAGGGGAGGGGGACCgCTCCGGGAAGGCCAGGGGACGGATTGGGGAAGGgCGGGTACCGA
AGCGGGgAAaTGGGggAaCcGGCGAGAGGGTTCCTCGCTAAGTGGGGGAAATaGGGGAAA
GGTTGACCAGTGGTtCCCcGCTCTCGTAACATGCCTCAGATAGCGCCATCCGCTGTACCT
GGtcaggtcGctggcaacttcggccgagcaggtgaacccgaaaggtgagggtcagtgtga
cacaccaaccgaacaccgacgaggcaagcgtaggagccggcgtggccgcgcccggcggcg
ctgaggactcctcg
But shows the output by skipping the first two lines.
What is the reason for this?
You don't need the while loop, or the readLine method. Just call jtextArea1.read(reader, "jTextArea1")
Edit: update following your comment. If you want to skip all lines starting with >, you will need to read the file manually and then append each line to your textArea.
So something like:
String line;
while ((line = reader.readLine()) != null)
{
if (!line.startsWith(">"))
{
jTextArea.append(line + "\n");
}
}
Use:
FileReader reader = new FileReader("filename.txt");
txtarea.read(reader, "filename.txt"); //Object of JTextArea
You need only the above two lines to read from a file and put it into JTextArea...
The problem must have been solved by the time, yet there's still no answer to the question why the first two lines are skipped.
You create reader and then read the first two lines from the file, remaining lines are loaded into jTextArea1.
Your code:
/* 1 */ while((textLine=reader.readLine())!=null){
/* 2 */ textLine = reader.readLine();
/* 3 */ jTextArea1.read(reader,"jTextArea1");
}
Line 1 reads the first line from the file. Then in the body of while you read the second line from the file at line 2. Line 3 reads the rest of the file into jTextArea1.
On the next iteration of the while loop, reader.readLine() returns null since the file is completely read.
To load text in a JTextComponent use its read method as suggested by Phill and Bhushankumar.
The second parameter to read is not used by JTextArea, so it's safe to pass null. This second parameter is usually used to store to URL of the loaded file to resolve relative references, for example links in an HTMLDocument.
textLine = reader.readLine(); is called twice...
Fixed:
try {
String textLine;
FileReader fr = new FileReader("ad.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null){
// textLine = reader.readLine(); // Remove this line
jTextArea1.read(reader, "jTextArea1");
}
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
Correctly is:
try {
FileReader fr = new FileReader("tablica.txt");
BufferedReader reader = new BufferedReader(fr);
do {
l.read(reader, null);
}
while ((textLine=reader.readLine()) != null)
;
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}

Read XML, Replace Text and Write to same XML file via Java

Currently I am trying something very simple. I am looking through an XML document for a certain phrase upon which I try to replace it. The problem I am having is that when I read the lines I store each line into a StringBuffer. When I write the it to a document everything is written on a single line.
Here my code:
File xmlFile = new File("abc.xml")
BufferedReader br = new BufferedReader(new FileReade(xmlFile));
String line = null;
while((line = br.readLine())!= null)
{
if(line.indexOf("abc") != -1)
{
line = line.replaceAll("abc","xyz");
}
sb.append(line);
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(xmlFile));
bw.write(sb.toString());
bw.close();
I am assuming I need a new line character when I prefer sb.append but unfortunately I don't know which character to use as "\n" does not work.
Thanks in advance!
P.S. I figured there must be a way to use Xalan to format the XML file after I write to it or something. Not sure how to do that though.
The readline reads everything between the newline characters so when you write back out, obviously the newline characters are missing. These characters depend on the OS: windows uses two characters to do a newline, unix uses one for example. To be OS agnostic, retrieve the system property "line.separator":
String newline = System.getProperty("line.separator");
and append it to your stringbuffer:
sb.append(line).append(newline);
Modified as suggested by Brel, your text-substituting approach should work, and it will work well enough for simple applications.
If things start to get a little hairier, and you end up wanting to select elements based on their position in the XML structure, and if you need to be sure to change element text but not tag text (think <abc>abc</abc>), then you'll want to call in in the cavalry and process the XML with an XML parser.
Essentially you read in a Document using a DocuemntBuilder, you hop around the document's nodes doing whatever you need to, and then ask the Document to write itself back to file. Or do you ask the parser? Anyway, most XML parsers have a handful of options that let you format the XML output: You can specify indentation (or not) and maybe newlines for every opening tag, that kinda thing, to make your XML look pretty.
Sb would be the StringBuffer object, which has not been instantiated in this example. This can added before the while loop:
StringBuffer sb = new StringBuffer();
Scanner scan = new Scanner(System.in);
String filePath = scan.next();
String oldString = "old_string";
String newString = "new_string";
String oldContent = "";
BufferedReader br = null;
FileWriter writer = null;
File xmlFile = new File(filePath);
try {
br = new BufferedReader(new FileReader(xmlFile));
String line = br.readLine();
while (line != null) {
oldContent = oldContent + line + System.lineSeparator();
line = br.readLine();
}
String newContent = oldContent.replaceAll(oldString, newString);
writer = new FileWriter(xmlFile);
writer.write(newContent);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
scan.close();
br.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories