Combining multiple lines into one single line - java

I have a text file which looks like this:
thiasisatest("test1",
"test2",
"test3",
"test4",
"test5");
The output I am trying to achieve is this:
thiasisatest("test1", "test2", "test3", "test4", "test5");
My code looks like this:
import java.io.*;
public class IoTest {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("/Applications/textfile.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine.trim().replace("\n", ""));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
I am reading the line and replacing all lines in the while loop, but the output doesn't change and the lines are still there when I am trying to print out the string.
What am I doing wrong?
Thank you for your help

You actually do not need to replace the line; Because you are technically recalling line by line.
All you need to do is create a StringBuilder to which you append every line from your buffered reader.
Your code should look like this
String sCurrentLine;
StringBuilder builder = new StringBuilder();
while ((sCurrentLine = br.readLine()) != null){
builder.append(sCurrentLine);
}
You can now output the content of the "builder" to another file.

System.out.println
terminates the line, that it why you are getting multiple lines.

Related

Combine a Read and Parse text.txt

Problem: I can't parse my file test.txt, by spaces. I can 1) read text files, and I can 2) parse strings, but I cannot connect the two and parse a text file! My purpose is to learn how to analyze text files. This is a simplified approach to that.
Progress: Thus far, I can read test.txt using FileReader and BufferedReader, and print it to console. Further, I can parse simple String variables. The individual operations run, but I'm struggling with parsing an actual text file. I believe this is because my test.txt is stored in the buffer, and after I .close() it, I can't print it.
Text File Content:
This is a
text file created, only
for testing purposes.
Code:
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.print(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
// readFileMethod a = new readFileMethod(line);
System.out.println(a.splitIt());
}
}
Preemptive thank you for your sharing your knowledge. Many posts on reading and parsing have been solved here on SO, but I've not the understanding to implement others' solutions. Please excuse me, I've only been learning Java a few months and still struggle with the basics.
Ok lets make the splitting into a mthod
private static void splitIt (String toTest) {
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece.
System.out.println(piece);
}
}
then you can call it from within
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt (line);
}
Building on Scary Wombat and your code, i made some changes.
It should now print the Line that is being read in and each word that is separated by space.
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public static void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.println(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line); // print the current line
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Java; New line for certain character in output with a file input

Basically the '{' and '}' need to be on new lines for the output. But i do not know how to read by certain characters efficiently. I have a program that reads the lines and outputs them and do not know where to start. Thanks
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
try {
FileReader reader = new FileReader("textfile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Here's a simple way to do it (using org.apache.commons.io for file parsing):
Solution
public static void main(String args[]) throws IOException {
File testFile = new File("textfile.txt");
String fileContent = FileUtils.readFileToString(testFile);
fileContent = fileContent.replaceAll("\\{", "\n{").replaceAll("}", "\n}");
System.out.println(fileContent);
}
Explanation
This will read the file to a String and replace all the occurrences of a '{' or '}' with a '\n{' or '\n}' correspondingly.
Btw. only the '{' character needs to be espaced via '\\'.
EDIT:
How to use the library.
Seeing that you seem to be new to Java, to use the library you have multiple options. One of them would be to use a project management tool such as "Apache Maven".
However the easiest option is to donwload the library (choose "commons-io-2.4-bin.zip").
Extract the file commons-io-2.4.jar into your project. Assuming you have a modern IDE it will know how to import the library when it is used in the code.
You could use the String.replaceAll method then you could add a new line and print the { to the new line
Here is how you could do it:
public static void main(String[] args) throws IOException {
try {
FileReader reader = new FileReader("textfile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
line=line.replaceAll("\\{", "\n{");
line=line.replaceAll("\\}", "\n}");
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
As you want to read file character wise. don't read line but character
while ((r = reader.read()) != -1) {
char ch = (char) r;
// do your work
}
}
If you want to read line first for some reason
One you get the line
char[] chars = line.toCharArray();
for (Char char : chars)
{
// check for that character and process accordingly
}

NullPointerException on Buffered Reader

I have this simple bit of code causing me a headache
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("Quiz.csv")));
List<String> lines = null;
String line = null;
try {
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
catch (Exception e)
{
Log.e(getLocalClassName(), e.toString());
}
I get a nullPointerException from logcat when I hit the while loop
Your lines is null. Initialise it:
List<String> lines = new ArrayList<String>();
You have to initialize lines like so:
List<String> lines = new ArrayList<String>();

Why Different outputs of bufferereader and scanner?

I have used two file reading classes , scanner and bufferedReader. While reading the code you have to avoid the part of one of them. I have written them together just for ease to understand. Now question is why i am getting errors while using buffered reader instead of scanner class for this code. Scanner works fine with this code. I am getting exception error at parseRecord method. In this code i am trying to parse a csv, i have several classes which are using its output but i am stuck here and wonder why bufferedReader is not working the same way as scanner.
public List<? extends ReportRecord> load() throws Exception {
List<SportPopularityReportRecord> records=new ArrayList<SportPopularityReportRecord>();
// first way using buffered reader, please ignore the scanner part below.
BufferedReader br;
try {
br= new BufferedReader(new FileReader(filePath.toString()));
String line=br.readLine();
if ((line = br.readLine()) != null)
{
parseHeader(line);
}
while(line != null)
{
line= br.readLine();
records.add(parseRecord(line));
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
br.close();
// fis.close();
}
}
// Second way using scanner class, please ignore the buffered reader part above.
String s;
Scanner sc=new Scanner(filePath.toFile());
//getting header
if(sc.hasNextLine()){
s=sc.nextLine();
parseHeader(s);
}
//getting recored
while(sc.hasNextLine()){
s=sc.nextLine();
records.add(parseRecord(s));
}
//sort the record
Collections.sort(records, new SportPopularityReportRecordComparator());
recordList=records;
//return record List
return recordList;
}
public SportPopularityReportRecord parseRecord(String strRecord) {
String [] s=strRecord.split(",");
SportPopularityReportRecord r=new SportPopularityReportRecord();
r.setSport(s[0]);
r.setRank(Integer.parseInt(s[1]));
return r;
}
try this it will work.
String line=br.readLine();
if (line != null)
{
parseHeader(line);
}
You are reading things two times.

Reading lines with BufferedReader and checking for end of file

If I have something like this in my code:
String line = r.readLine(); //Where r is a bufferedReader
How can I avoid a crash if the next line is the end of the file? (i.e. null)
I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.
If there is something there then all is OK, but I can't be guaranteed that there will be something there.
So if I do something like: (pseudo code):
if (r.readLine is null)
//End code
else {check line again and excecute code depending on what the next line is}
The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?
I've not worked out a way to do this - any suggestions would be a great help.
Am... You can simply use such a construction:
String line;
while ((line = r.readLine()) != null) {
// do your stuff...
}
If you want loop through all lines use that:
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
You can use the following to check for the end of file.
public bool isEOF(BufferedReader br)
{
boolean result;
try
{
result = br.ready();
}
catch (IOException e)
{
System.err.println(e);
}
return result;
}
In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.
String line = r.readLine();
while(line!=null){
System.out.println(line);
line = r.readLine();
}
A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class LineOperation {
public static void main(String[] args) throws IOException {
Files.newBufferedReader(Paths.get("C://xyz.txt")).
lines().
collect(Collectors.toSet()). // You can also use list or any other Collection
forEach(System.out::println);
}
}
You can do it via BufferReader. I know this is not relevant to following question. But I would post it for extra fact for a newbie who would not use BufferReader but Scanner for reading file.
A part from BufferReader you could use Java Scanner class to read the file and check the last line.
Buffer Reader
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line
}
}
Scanner
try {
Scanner scanner = new Scanner(new FileReader(file));
while (scanner.hasNext()) {
// Above checks whether it has or not ....
}
} catch (IOException e) {
e.printStackTrace();
}
If you use this code fragment in a multi threaded environment, go ahead with BufferReader since its synchronized.
In addition, BufferReader is faster than Scanner.
If you would like to do some check like:
if (reader.ready())
stringBuilder.append("#");
You can use ready()
public static void check() throws IOException {
InputStream in = new FileInputStream(new File(filePath));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
if (reader.ready())
stringBuilder.append("#");
}
String returnedString = stringBuilder.toString();
System.out.println(returnedString);
}
You could purposely have it throw the error inside your loop. i.e.:
String s = "";
while (true) {
try {
s = r.readline();
}catch(NullPointerException e) {
r.close();
break;
}
//Do stuff with line
}
what everyone else has sad should also work.

Categories

Resources