I tried this:
public static void ReadRecord()
{
String line = null;
try
{
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
line = br.readLine();
while(line != null)
{
System.out.println(line);
}
br.close();
fr.close();
}
catch (Exception e)
{
}
}
}
It non stop and repeatedly reads only one record that i had inputtd and wrote into the file earlier...How do i read records and use tokenization in reading records?
You have to read the lines in the file repeatedly in the loop using br.readLine(). br.readLine() reads only one line at time.
do something like this:
while((line = br.readLine()) != null) {
System.out.println(line);
}
Check this link also if you have some problems. http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Tokenization
If you want to split your string into tokens you can use the StringTokenizer class or can use the String.split() method.
StringTokenizer Class
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
st.hasMoreTokens() - will check whether any more tokens are present.
st.nextToken() - will get the next token
String.split()
String[] result = line.split("\\s"); // split line into tokens
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
line.split("\\s") - will split line with space as the delimiter. It returns a String array.
try this
while((line = br.readLine()) != null)
{
System.out.println(line);
}
Try This :
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
while((line=br.readline())!=null)
System.out.println(line);
For a text file called access.txt locate for example on your X drive, this should work.
public static void readRecordFromTextFile throws FileNotFoundException
{
try {
File file = new File("X:\\access.txt");
Scanner sc = new Scanner(file);
sc.useDelimiter(",|\r\n");
System.out.println(sc.next());
while (sc.hasNext()) {
System.out.println(sc.next());
}
sc.close();// closing the scanner stream
} catch (FileNotFoundException e) {
System.out.println("Enter existing file name");
e.printStackTrace();
}
}
Related
How do I skip the first element from a String Array?
Another quick approach is to control the line reads through flag like below:
public List<Beruf> fileRead(String filePath) throws IOException {
List<Beruf> berufe = new ArrayList<Beruf>();
String line = "";
try {
FileReader fileReader = new FileReader(filePath);
BufferedReader reader = new BufferedReader(fileReader);
Boolean firstLine = Boolean.TRUE;
while ((line = reader.readLine()) != null) {
if(firstLine) {
firstLine = Boolean.FALSE;
continue;
}
String[] attributes = line.split(";");
Beruf beruf = createBeruf(attributes);
berufe.add(beruf);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return berufe;
}
The easiest way to remove the header line would be to just read it before you enter your while loop.
String filePath = path;
FileReader fileReader = new FileReader(filePath);
BufferedReader reader = new BufferedReader(fileReader);
String headers = reader.readLine(); //This removes the first line from the BufferedReader
while ((line = reader.readLine()) != null) {
String[] attributes = line.split(";");
Beruf beruf = createBeruf(attributes);
berufe.add(beruf);
}
reader.close();
If you use java 8 or higher and are allowed to use streams you could also use the lines method of the Files class
Files.lines(Paths.get(filePath))
.skip(1) // skipping the headers
.map(line -> line.split(";"))
.map(attributes -> createBeruf(attributes))
.forEach(beruf -> berufe.add(beruf));
I have a text file -> 23/34 <- and I'm working on a Java program.
I want to store them out in String One = 23 and anotherString = 34 and put them together to one string to write them down in a text file, but it dosen't work. :( Everytime it makes a break. Maybe because the split method but I don't know how to separate them.
try {
BufferedReader in = new BufferedReader (new FileReader (textfile) );
try {
while( (textfile= in.readLine()) != null ) {
String[] parts = textfileString.split("/");
String one = parts[0];
}
}
}
When I print or store one + "/" + anotherString, it makes a line-break at one but I want it all in one line. :(
public static void main(String[] args) throws Exception {
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String string1 = line.split("/")[0];
String string2 = line.split("/")[1];
bw.write(string1 + string2 + "\n");
bw.flush();
}
br.close();
bw.close();
}
On file:
23/34
Resulted in output.txt containing:
2334
You need to read in each line, and split it on your designated character ("/"). Then assign string1 to the first split, and string2 to the second split. You can then do with the variables as you want. To output them to a file, you simply append them together with a + operator.
You have never shown us how you are writing the file, so we can't really help you with your code. This is a bit of a more modern approach, but I think it does what you want.
File infile = new File("input.txt");
File outfile = new File("output.txt");
try (BufferedReader reader = Files.newBufferedReader(infile.toPath());
BufferedWriter writer = Files.newBufferedWriter(outfile.toPath())) {
String line;
while ((line = reader.readLine()) != null) {
String parts[] = line.split("/");
String one = parts[0];
String two = parts[1];
writer.write(one + "/" + two);
}
} catch (IOException ex) {
System.err.println(ex.getLocalizedMessage());
}
InputStream stream = this.getClass().getResourceAsStream("./test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
String[] parts = currentLine.split("/");
System.out.println(parts[0] + "/" + parts[1]);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I am making a program that makes an user choose a file then the program reads from the file. Now I've been told to make the program using bufferedreader and string tokenizer. So far I got program opening the file and counting the number of lines. But the number of words is not so easy.
This is my code so far:
int getWords() throws IOException
{
int count = 0;
BufferedReader BF = new BufferedReader(new FileReader(f));
try {
StringTokenizer words = new StringTokenizer(BF.readLine());
while(words.hasMoreTokens())
{
count++;
words.nextToken();
}
BF.close();
} catch(FileNotFoundException e) {
}
return count;
}
Buffered reader can only read a line at a time but I don't know how to make it read more lines.
to count words you can use countTokens() instead of loop
to read all lines use
String line = null;
while(null != (line = BF.readLine())) {
StringTokenizer words = new StringTokenizer(line);
words.countTokens();//use this value as number of words in line
}
As you said, buffered reader will read one line at a time. So you have to read lines until there are no more lines. readLine() returns null when the end of file is reached.
So do something like this
int getWords() throws IOException {
int count = 0;
BufferedReader BF = new BufferedReader(new FileReader(f));
String line;
try {
while ((line = BF.readLine()) != null) {
StringTokenizer words = new StringTokenizer(line);
while(words.hasMoreTokens()) {
count++;
words.nextToken();
}
}
return count;
} catch(FileNotFoundException e) {
} finally {
BF.close();
}
// Either rethrow the exception or return an error code like -1.
}
How to remove all blank spaces and empty lines from a txt File using Java SE?
Input:
qwe
qweqwe
qwe
qwe
Output:
qwe
qweqwe
qwe
qwe
Thanks!
How about something like this:
FileReader fr = new FileReader("infile.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
if (!line.equals("")) // don't write out blank lines
{
fw.write(line, 0, line.length());
}
}
fr.close();
fw.close();
Note - not tested, may not be perfect syntax but gives you an idea/approach to follow.
See the following JavaDocs for reference purposes:
http://download.oracle.com/javase/7/docs/api/java/io/FileReader.html
http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html
Have a look at trim() function
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#trim()
Also, some code would be helpful...
...
Scanner scanner = new Scanner(new File("infile.txt"));
PrintStream out = new PrintStream(new File("outfile.txt"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
line = line.trim();
if(line.length() > 0)
out.println(line);
}
...
This my first time answering to a question in this site so please be understandable, after a lot of searching I have found this that works for me.
FileReader fr = new FileReader("Input_Code.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("output_Code.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
line=line.replaceAll("\\s+", " ").trim().concat("\n");
if (!line.equals("")) // don't write out blank lines
{
fw.write(line, 0, line.length());
}
}
fr.close();
fw.close();
Remove spaces for each line and do not consider empty and null lines:
String line = buffer.readLine();
while (line != null) {
line = removeSpaces(line);
//ignore empty lines
if (line.isEmpty()) return;
....code....
line = buffer.readLine();
}
public String removeSpaces (String arg)
{
Pattern whitespace = Pattern.compile("\\s");
Matcher matcher = whitespace.matcher(arg);
String result = "";
if (matcher.find()) {
result = matcher.replaceAll("");
}
return result;
}
Used to remove empty lines in same the file.
public static void RemoveEmptyLines(String FilePath) throws IOException
{
File inputFile = new File(FilePath);
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String inputFileReader;
ArrayList <String> DataArray = new ArrayList<String>();
while((inputFileReader=reader.readLine())!=null)
{
if(inputFileReader.length()==0)
{
continue;
}
DataArray.add(inputFileReader);
}
reader.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(FilePath));
for(int i=0;i<DataArray.size();i++)
{
bw.write(DataArray.get(i));
bw.newLine();
bw.flush();
}
bw.close();
}
package com.home.interview;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class RemoveInReadFile {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("Readme.txt"));
while(scanner.hasNext())
{
String line = scanner.next();
String lineAfterTrim = line.trim();
System.out.print(lineAfterTrim);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I think you just want a regex expression:
txt= txt.replaceAll("\\n\\s*\\n", "\n"); //remove empty lines
txt= txt.replaceAll("\\s*", ""); //remove whitespaces
As for reading/writing files, there are plenty of other resources to find out how to do that.
How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.