Reading from file. Android, Java - java

I have some problem with reading file with Scanner.
My file has a following format:
line 1(basic signs, f.e.: ##%%&&).
line 2(number of lines with data, f.e.: 70)
line 3(some info)
line 4-74(some data in any format with semiColon as a delimiter)
I need to implement loop which started from fourth line and allows me to fill my ListView.
How to solve this problem?
here is part of code:
Scanner read = null;
Pattern b = Pattern.compile(";|\\|\n ");
String BasicSign, NumberOfFields, barcode, name, type, amount, price;
try {
Log.d(LOG_TAG1, "--- Reading from spr: ---");
File file = Environment.getExternalStorageDirectory();
File textFile = new File(file.getAbsolutePath() + File.separator + "myFile1.spr");
read = new Scanner(textFile);
read.useDelimiter(b);
while (read.hasNext()) {
BasicSign = read.next();
NumberOfFields = read.next();
barcode = read.next();
name = read.next();
amount = read.next();
price = read.next();
tvBarcode.setText(barcode123);
tvMyName.setText(name);
tvType.setText(type);
tvPrice.setText(price);
}
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

You could process your textfile linewise and skip the first 3 lines and start in the 4th. This is a simple straight forward solution:
BufferedReader br = new BufferedReader(textfile);
br.readLine(); // skip line
br.readLine(); // skip line
br.readLine(); // skip line
String line = br.readLine(); // start in 4th line
while (line !=null) { // end of file not reached
Scanner read = new Scanner(line);
read.useDelimiter(b);
//your while loop and processing
line = br.readLine(); // read line for next iteration
}
br.close();

Related

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

Input and Output program

I am trying to get this program to read an input file line by line and then print it to an output file, so for example:
Input file contains:
cookies
cake
ice cream
I want the output file to display this:
Line 1: cookies
Line 2: cake
Line 3: ice cream
I cannot figure out how to do this however, so any help will be appreciated.
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String name = in.next();
FileReader file = new FileReader(name);
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while(line != null){
text += line;
line = reader.readLine();
}
reader.close();
System.out.print("Enter the output file: ");
String out = in.next();
FileWriter filew = new FileWriter(out);
BufferedWriter buffw = new BufferedWriter(filew);
buffw.write(text);
buffw.close();
System.out.print("File written!");
in.close();
}
}
The problem is with the loop like:
while(line != null){
text += line;
line = reader.readLine();
}
readLine method would eat up the new line character and hence you don't see it in the output file. You need to append a new line character at the end like:
while(line != null){
text += line;
text += '\n';
line = reader.readLine();
}
I would suggest you using StringBuilder instead of string concatenation like:
StringBuilder stringBuilder = ...
while ..
stringBuilder.append(line);
stringBuilder.append('\n');
...
You have to add the end of line character again, because readLine() removes it:
while(line != null){
text += line;
text +="\n";
line = reader.readLine();
}

Formatting string to get just words in a column

I have a text:
c:\MyMP3s\4 Non Blondes\Bigger!\Faster, More!_Train.mp3
I want to remove form this text these characters: :,\!._
And format the text then like this:
c
MyMP3s
4
Non
Blindes
Bigger
Faster
More
Train
mp3
And write all of this in a file.
Here is what I did:
public static void formatText() throws IOException{
Writer writer = null;
BufferedReader br = new BufferedReader(new FileReader(new File("File.txt")));
String line = "";
while(br.readLine()!=null){
System.out.println("Into the loop");
line = br.readLine();
line = line.replaceAll(":", " ");
line = line.replaceAll(".", " ");
line = line.replaceAll("_", " ");
line = System.lineSeparator();
System.out.println(line);
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Write.txt")));
writer.write(line);
}
And it doesn't work!
The exception:
Into the loop
Exception in thread "main" java.lang.NullPointerException
at Application.formatText(Application.java:25)
at Application.main(Application.java:41)
At the end of your code, you have:
line = System.lineSeperator()
This resets your replacements. Another thing to note is String#replaceAll takes in a regex for the first parameter. So you have to escape any sequences, such as .
String line = "c:\\MyMP3s\\4 Non Blondes\\Bigger!\\Faster, More!_Train.mp3";
System.out.println("Into the loop");
line = line.replaceAll(":\\\\", " ");
line = line.replaceAll("\\.", " ");
line = line.replaceAll("_", " ");
line = line.replaceAll("\\\\", " ");
line = line.replaceAll(" ", System.lineSeparator());
System.out.println(line);
The output is:
Into the loop
c
MyMP3s
4
Non
Blondes
Bigger!
Faster,
More!
Train
mp3

Breaking a file down and rewriting it in java

I'm working on trying to break down this file that contains state abbreviations, state names, and zip codes. Some of the zip codes are only 3 digit zip codes and for formatting purposes have to be rewritten(Ex. 005 should be 005-005). What I need help with is separating the state names and abbreviations from the zip codes so that I can format the 3 digit zip codes into 6 digit zip codes.
The layout of the file is like this:
NY New York 005 063 090-149
etc with the rest of the states... (Notice how New York is a 2 part name and how it has a 3 digit zip code of 005 and 063. That needs to be rewritten as 005-005 and 063-063)
Here is my code:
public class ZipsReader {
public static void main(String[] args){
//Gets the file name and reads it
try {
//Prompts user for an input file
Scanner console = new Scanner(System.in);
System.out.println("Input file: ");
String inputFileName = console.next();
//Prompts user for an output file
//System.out.println("Output file: ");
//String outputFileName = console.next();
//PrintWriter out = new PrintWriter(outputFileName);
//Reads the selected file line for line
File selectedFile = new File(inputFileName);
Scanner in = new Scanner(selectedFile);
while (in.hasNextLine()) {
String line = in.nextLine();
Scanner in2 = new Scanner(line);
//Reads the selected file word for word
while (in2.hasNext()){
String state = in2.isLetter();
String word = in2.next();
if (word.matches("\\d{3}-\\d{3}")){
System.out.println(word);
}
if (word.matches("\\d{3}")){
System.out.println(word + "-" + word);
}
}
in2.close();//closes the word scanner
}
console.close();//closes the file opener scanner
in.close();//closes the line scanner
//out.close();//closes the print writer
}
//Prints out message if file cant be found
catch (FileNotFoundException e) {
System.out.println("Sorry the file could not be found.");
}
//Needed to compile
finally {
}
}
}
The .matches String method works for getting the zip codes but I am not sure how to pick out the state abbrev. and names separately from the zip codes.
Right now I am just doing it to the console for time saving reasons for the time being but I will modify it to write to another file when I get this figured out.
Thanks for the help in advance
You can try this:
public class ZipReader {
public static void main(String[] args) {
//Gets the file name and reads it
try {
//Prompts user for an input file
Scanner console = new Scanner(System.in);
System.out.println("Input file: ");
String inputFileName = "G:\\test.txt";
//Prompts user for an output file
//System.out.println("Output file: ");
//String outputFileName = console.next();
//PrintWriter out = new PrintWriter(outputFileName);
//Reads the selected file line for line
File selectedFile = new File(inputFileName);
Scanner in = new Scanner(selectedFile);
String states="";
while (in.hasNextLine()) {
String line = in.nextLine();
Scanner in2 = new Scanner(line);
//Reads the selected file word for word
while (in2.hasNext()) {
//String state = in2.isLetter();
String word = in2.next();
if (word.matches("\\d{3}-\\d{3}")) {
System.out.println(word);
}
else if (word.matches("\\d{3}")) {
System.out.println(word + "-" + word);
}
else if(word.matches("[A-Z]{2}")){
System.out.println(word);
}
else{
states=states+word+" ";
}
}
System.out.println(states+"\n");
states="";
in2.close();//closes the word scanner
}
console.close();//closes the file opener scanner
in.close();//closes the line scanner
//out.close();//closes the print writer
} //Prints out message if file cant be found
catch (FileNotFoundException e) {
System.out.println("Sorry the file could not be found.");
} //Needed to compile
finally {
}
}
}

Retrieving certain variables from a text file

I'm trying to write a part of a program that reads a text file and then retrieves an integer from each line in the file and adds them together. I've managed to retrieve the integer, however each line contains more than one integer, leading me to inadvertently pick up other integers that I don't need. Is it possible to skip certain integers?
The format of the text file can be seen in the link underneath.
Text file
The integers that i'm trying to collect are the variables that are 3rd from the left in the text file above, (3, 6 and 4) however i'm also picking up 60, 40 and 40 as they're integers too.
Here's the code that i've got so far.
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
}
}
return itemAmount;
}
Just add input.nextLine():
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
input.nextLine();
}
From the documentation: nextLine advances the scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Another approach would be parsing each line and taking the third column.
BufferedReader r = new BufferedReader(new FileReader(filename));
while (true) {
String line = r.readLine();
if (line==null) break;
String cols[] line.split("\\s+");
itemAmount += Integer.parseInt(cols[2]);
}
r.close();
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
String []var = input.nextLine().split("\\s+");
itemAmount += var[2];
}
return itemAmount;
}

Categories

Resources