Java - Only read first line of a file - java

I only want to read the first line of a text file and put that first line in a string array.
This is what I have but its reading the whole file.
ex text in myTextFile:
Header1,Header2,Header3,Header4,Header5
1,2,3,4,5
6,7,8,9,10
String line= System.getProperty("line.separator");
String strArray[] = new String[5];
String text = null;
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
text = brTest .readLine();
while (text != line) {
System.out.println("text = " + text );
strArray= text.split(",");
}

use BufferedReader.readLine() to get the first line.
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
text = brTest .readLine();
System.out.println("Firstline is : " + text);

If I understand you, then
String text = brTest.readLine();
// Stop. text is the first line.
System.out.println(text);
String[] strArray = text.split(",");
System.out.println(Arrays.toString(strArray));

With Java 8 and java.nio you can also do the following:
String myTextFile = "path/to/your/file.txt";
Path myPath = Paths.get(myTextFile);
String[] strArray = Files.lines(myPath)
.map(s -> s.split(","))
.findFirst()
.get();
If TAsks assumption is correct, you can realize that with an additional
.filter(s -> !s.equals(""))

Also, beside of all other solutions presented here, you could use guava utility class (Files), like below:
import com.google.common.io.Files;
//...
String firstLine = Files.asCharSource(myTextFile).readFirstLine();

I think you are trying to get one line only if it's not empty.
You can use
while ((text=brTest .readLine())!=null){
if(!text.equals("")){//Ommit Empty lines
System.out.println("text = " + text );
strArray= text.split(",");
System.out.println(Arrays.toString(strArray));
break;
}
}

Use this
BuffereedReader reader = new BufferedReader(new FileReader(textFile));
StringBuilder builder = new StringBuilder();
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
break;
}
if(sb.toString.trim().length!=0)
System.out.println("first line"+sb.toString);

I hope this will help someone
to read the first line:
public static String getFirstLine() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = br.readLine();
br.close();
return line;
}
to read the whole text:
public static String getText() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line).append("\n");
line = br.readLine();
}
String fileAsString = sb.toString();
br.close();
return fileAsString;
}

You need to change the condition of your loop
String[] nextLine;
while((nextLine = brTest.readLine()) != null) {
...
}
ReadLine reads each line from beginning up to the occurrence of \r andor \n
You can also use tokenizer to split the string
String[] test = "this is a test".split("\\s");
In addition it seems the file is of type CSV if it is please mention that in the question.

Related

Simplest way to concatenate multi lines of text in java through File Handling

I tried concatenating 2 lines of text in a given text file and printing the output to the console. My code is very complicated, is there a simpler method to achieve this by using FileHandling basic concepts ?
import java.io.*;
public class ConcatText{
public static void main(String[] args){
BufferedReader br = null;
try{
String currentLine;
br = new BufferedReader(new FileReader("C:\\Users\\123\\Documents\\CS105\\FileHandling\\concat.file.text"));
StringBuffer text1 = new StringBuffer (br.readLine());
StringBuffer text2 = new StringBuffer(br.readLine());
text1.append(text2);
String str = text1.toString();
str = str.trim();
String array[] = str.split(" ");
StringBuffer result = new StringBuffer();
for(int i=0; i<array.length; i++) {
result.append(array[i]);
}
System.out.println(result);
}
catch(IOException e){
e.printStackTrace();
}finally{
try{
if(br != null){
br.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
The text file is as follows :
GTAGCTAGCTAGC
AGCCACGTA
the output should be as follows (concatenation of the text file Strings) :
GTAGCTAGCTAGCAGCCACGTA
If you are using java 8 or newer, the simplest way would be:
List<String> lines = Files.readAllLines(Paths.get(filePath));
String result = String.join("", lines);
If you are using java 7, at least you can use try with resources to reduce the clutter in the code, like this:
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
StringBuffer text1 = new StringBuffer (br.readLine());
StringBuffer text2 = new StringBuffer(br.readLine());
// ...
}catch(IOException e){
e.printStackTrace();
}
This way, resources will be autoclosed and you don't need to call br.close().
Short answer, there is:
public static void main(String[] args) {
//this is called try-with-resources, it handles closing the resources for you
try (BufferedReader reader = new BufferedReader(...)) {
StringBuilder stringBuilder = new StringBuilder();
String line = reader.readLine();
//readLine() will return null when there are no more lines
while (line != null) {
//replace any spaces with empty string
//first argument is regex matching any empty spaces, second is replacement
line = line.replaceAll("\\s+", "");
//append the current line
stringBuilder.append(line);
//read the next line, will be null when there are no more
line = reader.readLine();
}
System.out.println(stringBuilder);
} catch (IOException exc) {
exc.printStackTrace();
}
}
First of all read on try with resources, when you are using it you don't need to close manually resources(files, streams, etc.), it will do it for you. This for example.
You don't need to wrap read lines in StringBuffer, you don't get anything out of it in this case.
Also read about the methods provided by String class starting with the java doc - documentation.

how to save contents of a file as single string using java

I am trying to extract a specific content from text file by using delimiters. This is my code :
File file = new File("C:\\Inputfiles\\message.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st=br.readLine()) != null) {
String[] strings = StringUtils.split(st, "------------");
System.out.println(strings);}
But as a result, each and everyline is getting splitted by delimiter and saved as array.
Can anyone suggest how I can save the contents from file as a single string, so I can get limited number of lines only as Array.
You can use StringBuilder or StringBuffer to do that.
File file = new File("C:\\Inputfiles\\message.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st=br.readLine()) != null) {
String[] strings = StringUtils.split(st, "------------");
StringBuilder singleString = new StringBuilder();
for(String s : strings){
singleString.append(s);
}
System.out.println(singleString.toString());
}
Thanks All,
I did using below changes
String contents = new String(Files.readAllBytes(Paths.get("C:\\Inputfiles\\message1.txt")));
String[] splitted = StringUtils.split(contents, "-------");
for(int i=0;i<splitted.length;i++)
System.out.println(splitted[i]);

remove "," from each line and put to arraylist in java

Content of a file:
Afganistan,5,1,648,16,10,2,0,3,5,1,1,0,1,1,1,0,green,0,0,0,0,1,0,0,1,0,0,black,green
Albania,3,1,29,3,6,6,0,0,3,1,0,0,1,0,1,0,red,0,0,0,0,1,0,0,0,1,0,red,red
Algeria,4,1,2388,20,8,2,2,0,3,1,1,0,0,1,0,0,green,0,0,0,0,1,1,0,0,0,0,green,white
American-Samoa,6,3,0,0,1,1,0,0,5,1,0,1,1,1,0,1,blue,0,0,0,0,0,0,1,1,1,0,blue,red
Andorra,3,1,0,0,6,0,3,0,3,1,0,1,1,0,0,0,gold,0,0,0,0,0,0,0,0,0,0,blue,red
Angola,4,2,1247,7,10,5,0,2,3,1,0,0,1,0,1,0,red,0,0,0,0,1,0,0,1,0,0,red,black
Anguilla,1,4,0,0,1,1,0,1,3,0,0,1,0,1,0,1,white,0,0,0,0,0,0,0,0,1,0,white,blue
I need to remove "," from the lines and put each line into an array separately.
The content of one line should be separate from other line using java
I used ArrayList but array includes commas.
Please help me remove "," from each line.
This is the code I have used so far:
String filePath = "/home/pavan/Desktop/flag.data";
try
{
BufferedReader lineReader = new BufferedReader(new FileReader(filePath));
String lineText = null;
List<String> listLines = new ArrayList<String>();
while ((lineText = lineReader.readLine()) != null)
{
String a = lineText.replaceAll(",", "");
listLines.add(a);
}
lineReader.close();
for (String line : listLines)
{
System.out.println(line);
}
}catch(IOException ex){
System.err.println(ex);
}
String [] newArray = yourString.split(",");

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

How can I overwrite lines from text file to specific lines in another file instead of appending them

public class AddSingleInstance {
public void addinstances(String txtpath,String arffpath) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("C:\\src\\text.txt"));
FileWriter fw = new FileWriter("C:\\src\\" + test.txt,true);
StringBuilder sb = new StringBuilder();
//String toWrite = "";
String line = null;
while ((line = reader.readLine())!= null){
// toWrite += line;
sb.append(line);
sb.append("\n");
}
reader.close();
fw.write(sb.toString());
fw.flush();
fw.close();
}
}
my code is working on append lines from text file(A) to specific lines in another file(B), like
I
AM
......
(above lines are fixed, cannot be overwriting)
student(New string was added from text file)
now(New string...)
How can I overwrite those lines into file(B) instead of appending them on B?
You can use java.io.RandomAccessFile to access file(B) and write to it at the desired location.

Categories