how to use String method inside while loop - java

i am trying to use String method inside while loop so i can read part of the file the code is this
package AnimeAid;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReadFile {
public void getFileInformation() throws IOException {
try{
String file;
file = "tra.srt";
Charset charset = Charset.defaultCharset();
Path path = Paths.get(file);
BufferedReader reader = Files.newBufferedReader(path, charset);
System.out.printf("Lines from %s:%n",file);
String line;
int num = 5;
while((line = reader.readLine()) != null && line.indexOf(':') != -1){
System.out.println(line.substring(0, 10));
}
}catch(FileNotFoundException ex){
System.err.println(ex);
}
}
}
now it not give me any error message but it is not giving the right answer and i need to use return not system.out.print
Lines from tra.srt:
BUILD SUCCESSFUL (total time: 0 seconds)
how file look like
1
00:00:01,600 --> 00:00:04,080
<b>Mr Magnussen, please state your
full name for the record.</b>
2
00:00:04,080 --> 00:00:07,040
Charles Augustus Magnussen.
the output most be the timing 00:00:01,600 from every line how he know by looking for every : sign

line.indexOf(':')
returns an integer. This means you have while (boolean && int) which makes no sense in a Java world. You should compare the result of the indexOf method in order to get there a boolean as well.
Eg:
while((line = reader.readLine()) != null && line.indexOf(':') != -1)

Related

Buffered Reader, Line count, Split, Parse in Java

Actually, I am assigned a task where I have a xyz.txt/CSV file which will basically have numeric values and I am supposed to pass it through BUFFERED READER then split those values and finally parse them.
So I have a Java code can body help me with it.
package javaapplication12;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class JavaApplication12 {
public static void main(String[] args) {
String count= "F:\\Gephi\\number.txt";
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(count);
br = new BufferedReader
// AT THIS POINT THERE SHOULD BE SOME THING THAT COUNTS NUMBER OF LINES USING COUNT++ OR SOMETHING LIKE THIS//
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
// COMING TO THIS POINT THE ABOVE VALUES OF .TXT FILE SHOULD BE SPLIT USING SPLIT PARAMETER//
// AFTER SPLITTING THE SPLIT VALUE SHOULD BE KEPT IN AN ARRAY AND THEN EVENTUALLY PARSED//
Or IF Anybody can rewrite the code in another way of the above-stated problem, it shall also be appreciated.
Here is my solution with Java 8:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
public class BR {
public static void main(String[] args) {
String fileName = "br.txt";
//for the csv format
String regex = ", ";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
List<String[]> lines = br.lines()
.map(line -> line.split(regex))
.collect(Collectors.toList());
parse(lines);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void parse(List<String[]> lines) {
//Do your stuff here
}
}
The initialization of the BufferedReader is in the try block (this approach is called try with resources), since BufferedReader implements AutoCloseable (an interface), so in case an exception is thrown the reader will close.
The br.lines() method returns all lines from the file.
In the map function you are passing a line that is rad in a lambda. The line is split using the split variable (for CSV format it is ', ') and is returned and collected.
The result is a List of arrays of String which can be changed in the body of the map function.
For more clarification I suggest you check some Java 8 tutorials and you will fully understand what is going on.
This solution might not be appropriate for your knowledge level (I guess), but hope it inspires you to check some fancier and modern approaches.
Have a nice day.

Java: Read from Multiple Lines (External File)

I am trying to display the contents of multiple rows in a text file. I can do it no problem with a single line, but I add another line and I'm not sure what I need to add to my code to make it move on to the next line. I need myValues[1] to be the same as myValues[n] only to be the second line in the file. I believe I need to se a new String as the next line but I'm not sure exactly how with this setup.
package a3;
import java.io.*;
public class A3
{
public static void main(String [] args)
{
String animals = "animals.txt";
String line = null;
try
{
FileReader fileReader = new FileReader(animals);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String aLine = bufferedReader.readLine();
String myValues[] = aLine.split(" ");
int n = 0;
while((line = bufferedReader.readLine()) != null)
{
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
bufferedReader.close();
}
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + animals + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + animals + "'");
}
}
}
Here is another simple way to read lines from a file and do the processing:
There is a java.io.LineNumberReader class which helps do it.
Sample snippet:
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
String line = null;
while ((line = lnr.readLine()) != null)
{
// Do you processing on line
}
In your code, the array myValues is never changed and always contains the values for the first line of text. You need to change it each time you get a new line, this is done in your while loop :
[...]
while((line = bufferedReader.readLine()) != null)
{
myValues[] = line.split(" ");
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
Obviously not tested...
You could also read all lines to a String list like this:
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;
List<String> lines = Files.readAllLines(new File(animals).toPath(), Charset.defaultCharset());
And than iterate over the line list, split the values and output them.

Read windows filename from file in Java

Background
For a program I'm writing I need to be able to read Windows filenames from a file. Unfortunately, Windows use \ instead of /, which makes this tricky. I've been trying different ways, but it never seems to work. Here's the Java code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test {
static String localFile;
static String localFilePrefix;
static String user;
public static void main(String[] args){
readConfig("user.txt");
}
public static boolean readConfig(String cfgFilePath){
try{
BufferedReader reader = new BufferedReader(new FileReader(cfgFilePath));
try{
String line;
while((line = reader.readLine()) != null){
if(line.indexOf("User") != -1){
user = line.substring(line.indexOf(" ")+1);
}else if(line.indexOf("LocalFile") != -1){
String tmp = line.substring(line.indexOf(" ")+1);
System.out.println("Test: " + tmp);
setLocalFile(tmp);
}
}
}catch(IOException ee){
System.err.println(ee.getMessage());
}
}catch(FileNotFoundException e){
System.err.println(e.getMessage());
}
return true;
}
public static void setLocalFile(String lFileName){
System.out.println("FileName: " + lFileName);
localFile = lFileName;
if(new File(localFile).isDirectory()){
System.out.println("Here!");
localFilePrefix=localFile+File.separator;
}
}
}
And here is the config file:
User test
LocalFile C:\User
Running this code, whith that file path, doesn't print Test: C:\Users, which it should. Neither does it print FileName: C:\Users or Here!. If I remove "Users" from the file path, however, it works fine and prints everything it's supposed to. It even recognizes C:\ as a directory.
Question
I don't want the user to be forced to write the file path in a special format just because my program can't handle it. So how can I fix this?
Your first condition line.indexOf("User") != -1 is true for the input User test but also for LocalFile C:\User (and it will be so for every path that contains User). Therefore, the else if condition is not evaluated.
Use .startsWith instead of .indexOf
while ((line = reader.readLine()) != null) {
if (line.startsWith("User")) {
user = line.substring(line.indexOf(" ") + 1);
} else if (line.startsWith("LocalFile")) {
String tmp = line.substring(line.indexOf(" ") + 1);
System.out.println("Test: " + tmp);
setLocalFile(tmp);
}
}

Java replace specific string in text file

I've got a text file called log.txt.
It's got the following data
1,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg
2,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg
The numbers before the first comma are indexes that specify each item.
What I want to do is to read the file and then replace one part of the string(e.g. textFiles/a.txt) in a given line with another value(e.g. something/bob.txt).
This is what I have so far:
File log= new File("log.txt");
String search = "1,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg;
//file reading
FileReader fr = new FileReader(log);
String s;
try (BufferedReader br = new BufferedReader(fr)) {
while ((s = br.readLine()) != null) {
if (s.equals(search)) {
//not sure what to do here
}
}
}
You could create a string of total file content and replace all the occurrence in the string and write to that file again.
You could something like this:
File log= new File("log.txt");
String search = "textFiles/a.txt";
String replace = "replaceText/b.txt";
try{
FileReader fr = new FileReader(log);
String s;
String totalStr = "";
try (BufferedReader br = new BufferedReader(fr)) {
while ((s = br.readLine()) != null) {
totalStr += s;
}
totalStr = totalStr.replaceAll(search, replace);
FileWriter fw = new FileWriter(log);
fw.write(totalStr);
fw.close();
}
}catch(Exception e){
e.printStackTrace();
}
One approach would be to use String.replaceAll():
File log= new File("log.txt");
String search = "textFiles/a\\.txt"; // <- changed to work with String.replaceAll()
String replacement = "something/bob.txt";
//file reading
FileReader fr = new FileReader(log);
String s;
try {
BufferedReader br = new BufferedReader(fr);
while ((s = br.readLine()) != null) {
s.replaceAll(search, replacement);
// do something with the resulting line
}
}
You could also use regular expressions, or String.indexOf() to find where in a line your search string appears.
Solution with Java Files and Stream
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
private static void replaceAll(String filePath, String text, String replacement) {
Path path = Paths.get(filePath);
// Get all the lines
try (Stream<String> stream = Files.lines(file, StandardCharsets.UTF_8)) {
// Do the replace operation
List<String> list = stream.map(line -> line.replace(text, replacement)).collect(Collectors.toList());
// Write the content back
Files.write(file, list, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.error("IOException for : " + file, e);
e.printStackTrace();
}
}
Usage
replaceAll("test.txt", "original text", "new text");
A very simple solution would be to use:
s = s.replace( "textFiles/a.txt", "something/bob.txt" );
To replace all occurrences, use replaceAll shown in another proposal, where a regular expression is used - take care to escape all magic characters, as indicated there.

Java: deleting text in an csv which starts with --

I am loading a csv file and kept alive without closing BufferReader. Now I want to delete all lines which starts with -- and save that csv in a temp CSV. Anybody have an idea how I can do this find only c# code.
I tried to fix with regular expression but I failed.
An example of the csv:
-- DDL- "T453453 "."BMG"
-- DDL- "T423342 "."BMG234"
CREATE TABLE "T453453 "."BMG"
-- DDL- "T42234234 "."BMG236"
So it works but i have the last problem how i can add \n (Newline) cause if i debug this code i get the text in one line.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class CsV {
public static String Read() throws IOException{
return new String(Files.readAllBytes(Paths.get("C://Users//myd//Desktop//BW//BWFormated.csv")));
}
public static void main(String[] args) throws IOException {
File inputFile = new File("C://Users//myd//Desktop//BW//BWtest.csv");
File tempFile = new File("C://Users//myd//Desktop//BW//BWFormated.csv");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "--";
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write(currentLine);
}
writer.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(Read());
}
}
You can check each line, if it begins with -- using String.startsWith() method.
If so, read the next line and if the line has content you want to make other things with, you can put it into a list. Maybe like this:
String line;
List<String> list = new ArrayList<String>();
while((line = reader.readLine()) != null)
{
if(line.startsWith("--"))
continue;
list.add(line);
}
for(int i = 0; i < list.length; i++)
{
line = list.get(i);
// use regular expressions to extract the data you want to convert into CSV format
}
Hint: I didn't check my syntax, so it could be, that it won't be compiled ;-)
Use the Pattern class for regular expressions and maybe this tutorial will help you.
Good luck!
EDIT
Extend your while-loop to the following, which allows you to add new lines, too:
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove))
continue;
writer.write(currentLine);
writer.newLine(); // Writes a line separator.
}
Read the docs to the newLine() method.

Categories