The file begins with about 200 lines of background information that i don't need. Im trying to skip/ignore those 200 lines until a string is found. Once this string is found I want to be able to continue processing the rest of the text file.
Sample Text File:
(up to around line 240 is all the lines i need to skip/ignore)
http://pastebin.com/5Ay4ad6y
public static void main(String args[]) {
String endOfSyllabus = "~ End of Syllabus";
Path objPath = Paths.get("2014HamTechnician.txt");
if (Files.exists(objPath)) {
File objFile = objPath.toFile();
try (BufferedReader in = new BufferedReader(new FileReader(objFile))) {
String line = in.readLine();
while (line != null) {
line = in.readLine();
}
if(endOfSyllabus.equals(line) ){
restOfTextFile = line.split(endOfSyllabus);
}
}
System.out.println(restOfTextFile[0]);
}
catch(IOException e){
System.out.println(e);
}
}
else{
System.out.println(
objPath.toAbsolutePath() + " doesn't exist");
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new A19015_Form().setVisible(true);
}
});
}
You can try this if you know the exact string that you are looking
if (lineString.startsWith("insert exact string")) {
// ...
}
What about:
boolean found = false;
for (String line; (line = in.readLine()) != null;) {
found = found || line.equals(endOfSyllabus);
if (found) {
// process line
}
}
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class Test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
List<String> lines = FileUtils.readLines(new File("test.txt"));
List<String> avLines = new ArrayList<>();
boolean valid = false;
for (String line : lines) {
if (line.trim().equals("~ End of Syllabus")) {
valid = true;
continue;
}
if (valid) {
avLines.add("\n"+line);
}
}
System.out.println(avLines.size());
}
}
Related
I'm trying to take every single words from a text file and put them into a ArrayList but the StringTokenizer doesn't read the first line of the text file... What's wrong?
public class BufferReader {
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader("C://Java-projects//EsameJava//prova.txt"));
String line = reader.readLine();
List<String> str = new ArrayList<>();
while ((line = reader.readLine()) != null) {
StringTokenizer token = new StringTokenizer(line);
while (token.hasMoreTokens()) {
str.add(token.nextToken());
}
}
System.out.println(str);
The only solution I found is to start the text file from the second line but it's not what I want...
This is how you could marry the (very) old and the new(er) to provide a collection of words:
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WordCollector {
public static void main(String[] args) {
try {
List<String> words = WordCollector.getWords(Files.lines(Paths.get(args[0])));
System.out.println(words);
} catch (Throwable t) {
t.printStackTrace();
}
}
public static List<String> getWords(Stream<String> lines) {
List<String> result = new ArrayList<>();
BreakIterator boundary = BreakIterator.getWordInstance();
lines.forEach(line -> {
boundary.setText(line);
int start = boundary.first();
for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
String candidate = line.substring(start, end).replaceAll("\\p{Punct}", "").trim();
if (candidate.length() > 0) {
result.add(candidate);
}
}
});
return result;
}
}
I have a record in a CSV file and i am trying to add some extra info (a name) to the same specific record with the following code but it does not work. There is no error shown but the info i am trying to add just does not appear. What am i missing ?
public class AddName {
public static void main(String[] args) {
String filepath="Zoo.csv";
String editTerm="Fish";
String addedName="Ron";
addToRecord(filepath,editTerm,addedName);
}
public static void addToRecord(String filepath,String editTerm,String addedName){
String animal= "";
try{
FileWriter fw=new FileWriter(filepath,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
if (animal.equals(editTerm)){
pw.println(editTerm+","+addedName);
pw.flush();
pw.close();
}
System.out.println("Your Record was saved");
}
catch(Exception e){
System.out.println("Your Record was not saved");
e.printStackTrace();
}
}
You could consider using a CSV library to help you out with parsing CSVs because it is more complicated than it looks, especially when it comes down to quoting.
Here's a quick example using OpenCSV that clones the original CSV file and adds "Ron" as necessary:
public class Csv1 {
public static void main(String[] args) throws IOException, CsvValidationException {
addToRecord("animal.csv", "animal-new.csv", "fish", "Ron");
}
public static void addToRecord(String filepathIn, String filepathOut, String editTerm, String addedName)
throws IOException, CsvValidationException {
try (CSVReader reader = new CSVReader(new FileReader(filepathIn))) {
try (CSVWriter writer = new CSVWriter(new FileWriter(filepathOut))) {
String[] values;
while ((values = reader.readNext()) != null) {
if (values.length > 2 && values[0].equals(editTerm)) {
values[1] = addedName;
}
writer.writeNext(values);
}
}
}
}
}
Given the file:
type,name,age
fish,,10
cat,,12
lion,tony,10
will produce:
"type","name","age"
"fish","Ron","10"
"cat","","12"
"lion","tony","10"
(You can look for answers about outputting quotes in the resulting CSV)
Here the requirement is to add an extra column if the animal name matches. It's equivalent to changing a particular line in a file. Here's a simple approach to achieve the same, (Without using any extra libraries),
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class EditLineInFile {
public static void main(String[] args) {
String animal = "Fish";
Path path = Paths.get("C:\\Zoo.csv");
try {
List<String> allLines = Files.readAllLines(path);
int counter = 0;
for (String line : allLines) {
if (line.equals(animal)) {
line += ",Ron";
allLines.set(counter, line);
}
counter++;
}
Files.write(path, allLines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You may use this code to replace the file content "Fish" to "Fish, Ron"
public static void addToRecord(String filepath, String editTerm, String addedName) {
try (Stream<String> input = Files.lines(Paths.get(filepath));
PrintWriter output = new PrintWriter("Output.csv", "UTF-8"))
{
input.map(s -> s.replaceAll(editTerm, editTerm + "," + addedName))
.forEachOrdered(output::println);
} catch (IOException e) {
e.printStackTrace();
}
}
For now, I'm searching through the first one then sending it to the second one but the second one only prints and compares the first line.
I don't know how to make the second method start from the next line and so on. The objective is to do this with three text files but i cant even get through the first one. It has to be using bufferedreader and a while loop.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
public class scanner {
public static String line;
public static String line2;
public static String line3;
public static boolean match = false;
public static void main (String [] args) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("creditCards1.txt"));
line = in.readLine();
while (match==false && line != null)
{
System.out.println(line);
line = in.readLine();
scan2(line);
}
in.close();
}
public static boolean scan2(String line) throws IOException
{
BufferedReader in2 = new BufferedReader(new FileReader("creditCards2.txt"));
if (line2 == null || line2 == "7120-0824-9323-2825")
{
line2 = in2.readLine();
}
while(match==false && line!=null)
{
System.out.println(line2);
if(line2 == line)
{
match = true;
System.out.println("sdsds" + line);
in2.close();
break;
}
line2= in2.readLine();
break;
}
return match;
}
}
package so;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
File f1 = new File("/home/guest/Desktop/file1.txt");
File f2 = new File("/home/guest/Desktop/file2.txt");
File f3 = new File("/home/guest/Desktop/file3.txt");
try {
compareTwo(f1, f2);
compareTwo(f1, f3);
compareTwo(f2, f3);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void compareTwo(File f1, File f2) throws IOException {
String l1,l2;
try (BufferedReader r1 = new BufferedReader(new FileReader(f1))) {
while ((l1 = r1.readLine()) != null) {
try (BufferedReader r2 = new BufferedReader(new FileReader(f2))) {
while ((l2 = r2.readLine()) != null) {
if(l1.equals(l2))
System.out.println("line: " + l1 + " in file " + f1 + " exists in file " + f2);
}
}
}
}
}
}
public class scripttest {
public static void main(String[] args) {
File file = new File("text.txt");
script(file);
}
public static void script(File filename) {
String line = null;
try {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
bufferedReader.close();
} catch(IOException ex) {
System.out.println("Error reading file named '" + filename + "'");
}
}
}
Im trying to make a script function for my program, the script requires a file, which each command written out on each line to be carried out consecutively. How do I add the first three words on each line to an arraylist, which will then be used to interpret the commands for each line?
// considering you have line variable. myArrayList is ur list.
String[] words = line.split(" ");
if(words.length() >= 3) {
myArrayList.add(words[0] + " " + words[1] + " " + words[2])
}
If you can use Java 8:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TestScript {
public static void main(String[] args) {
script("text.txt");
}
private static void script(String filename) {
try (Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(TestScript::executeLine);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void executeLine(String line) {
System.out.println(line);
String[] args = line.split(" ");
executeCommand(Arrays.stream(args).limit(3).collect(Collectors.toList()),
Arrays.stream(args).skip(3).collect(Collectors.toList()));
}
private static void executeCommand(List<String> command, List<String> args) {
System.out.println(command + ": " + args);
}
}
I am trying to check if a file content is empty or not. I have a source file where the content is empty.
I tried different alternatives.But nothing is working for me.
Here is my code:
Path in = new Path(source);
/*
* Check if source is empty
*/
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br.readLine().length() == 0) {
/*
* Empty file
*/
System.out.println("In empty");
System.exit(0);
}
else{
System.out.println("not empty");
}
} catch (IOException e) {
e.printStackTrace();
}
I have tried using -
1. br.readLine().length() == 0
2. br.readLine() == null
3. br.readLine().isEmpty()
All of the above is giving as not empty.And I need to use -
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
Instead of new File() etc.
Please advice if I went wrong somewhere.
EDIT
Making little more clear. If I have a file with just whitespaces or
without white space,I am expecting my result as empty.
You could call File.length() (which Returns the length of the file denoted by this abstract pathname) and check that it isn't 0. Something like
File f = new File(source);
if (f.isFile()) {
long size = f.length();
if (size != 0) {
}
}
To ignore white-space (as also being empty)
You could use Files.readAllLines(Path) and something like
static boolean isEmptyFile(String source) {
try {
for (String line : Files.readAllLines(Paths.get(source))) {
if (line != null && !line.trim().isEmpty()) {
return false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Default to true.
return true;
}
InputStream is = new FileInputStream("myfile.txt");
if (is.read() == -1) {
// The file is empty!
} else {
// The file is NOT empty!
}
Of course you will need to close the is and catch IOException
You can try something like this:
A Utility class to handle the isEmptyFile check
package com.stackoverflow.answers.mapreduce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HDFSOperations {
private HDFSOperations() {}
public static boolean isEmptyFile(Configuration configuration, Path filePath)
throws IOException {
FileSystem fileSystem = FileSystem.get(configuration);
if (hasNoLength(fileSystem, filePath))
return false;
return isEmptyFile(fileSystem, filePath);
}
public static boolean isEmptyFile(FileSystem fileSystem, Path filePath)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileSystem.open(filePath)));
String line = bufferedReader.readLine();
while (line != null) {
if (isNotWhitespace(line))
return false;
line = bufferedReader.readLine();
}
return true;
}
public static boolean hasNoLength(FileSystem fileSystem, Path filePath)
throws IOException {
return fileSystem.getFileStatus(filePath).getLen() == 0;
}
public static boolean isWhitespace(String str) {
if (str == null) {
return false;
}
int length = str.length();
for (int i = 0; i < length; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
public static boolean isNotWhitespace(String str) {
return !isWhitespace(str);
}
}
Class to test the Utility
package com.stackoverflow.answers.mapreduce;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
public class HDFSOperationsTest {
public static void main(String[] args) {
String fileName = "D:/tmp/source/expected.txt";
try {
Configuration configuration = new Configuration();
Path filePath = new Path(fileName);
System.out.println("isEmptyFile: "
+ HDFSOperations.isEmptyFile(configuration, filePath));
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}