Reading character files between specific word in java - java

I have a java file, FileJava.java like this:
public class FileJava {
public static void main(String args[]) {
for (int i = 0; i < 5; i++) {
}
}
}
Then, i read above code line by line using this code:
import java.util.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("FileJava.java");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("for"))
{
lines.add("long A=0;");
if(line.contains("(") && line.contains(")")){
String get = line;
String[] split = get.split(";");
String s1 = split[0];
String s2 = split[1];
String s3 = split[2];
}
}
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
The question is, how to read character between '(' and ')' inside (for) in the FileJava.java, the character i mean "int i = 0; i < 5; i++" that will be stored in a variable, i have split based on ";", but when i print, the value :
s1 = for (int i = 0
s2 = i < 5
s3 = i++) {
While i expect:
s1 = int i = 0
s2 = i < 5
s3 = i++
Thanks

To answer your question how to restrict the splitting to the parenthesized section:
String[] split =
get.substring( get.indexOf('(')+1, get.indexOf(')').split("\\s*;\\s*");
Edit to address another prob.
Printing of the file will all happen in one line, because BufferedReader.readLine strips the line ends (LF, CRLF) from the line it returns. Thus, add a line break when writing:
for(String s : lines){
out.write(s);
out.newLine();
}

int index1 = line.indexOf("(");
int index2 = line.indexOf(")");
line = line.subString(index1 + 1, index2);

Its because you are splitting on ';' for the input
for (int i = 0; i < 5; i++) {
which will return all the characters between ';'
You can write a new method, called getBracketContent for example, that will be something like
String getBracketContent(String str)
{
int startIdx = str.indexOf('(')
int endIdx = str.indexOf(')')
String content = str.subString(startIdx + 1, endIdx);
}
then your code would be
if(line.contains("(") && line.contains(")")){
String get = getBracketContent(line);
String[] split = get.split(";");
Ideally I would use regular expressions to parse the information you need, but that is probably something you may want to look into later.

If you want to read the contents of a java file, you would be much better off using an AST (Abstract Syntax Tree) parser which will read in the contents of the file and then callback when it encounters certain expressions. In your case, you can listen just for the 'for' loop.

Related

Extra charcters in .csv output

After importing a CSV file and sorting it in to a 2-Dimensional array I get a couple of weird characters in only the first and possibly the last cell.
Expected output: S1358_R1
Actual output: S1358_R1
Does anyone know why these extra characters show up? The code used to do this is included below:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class open2 {
public static void main(String[] args) {
String line = "";
String splitBy = ",";
try {
//parsing a CSV file into BufferedReader class constructor
int i = 0;
String[][] ss = new String[10000][10000];
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\micha\\Documents\\spreadsheet.csv"));
while ((line = br.readLine()) != null) //returns a Boolean value
{
String[] cells = line.split(splitBy);
for (int j = 0; j < cells.length; j++) {
ss[i][j] = cells[j];
} // use comma as separator
i = i + 1;
}
System.out.println(ss[0][0]);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Compare user string input to a string from a textfile

I'm trying to do a simple login from a textfile. I've used different ways of reading the text from the file to a String line(BufferedReader and Scanner). I am able to get the line into a string, but it doesn't want to compare the 2 strings and match when I use an if statement(.equals()) or even if I use .equalsIgnoreCase(). When I print the 2 strings to be compared they are the same. but my if statement doesn't seem to return true?
This was the last coding i tried (I thought maybe if I put it into an array it would compare true, but still nothing).
Iv'e looked and saw similar questions to comparing strings from textfile, but never saw a problem with the if statement to return true
import java.io.*;
import java.text.*;
import java.lang.*;
public class tes
{
public static void main(String[] args)throws Exception
{
String logline = "JMX^1234";
ArrayList<String> lines = new ArrayList<String>();
FileReader fr = new FileReader("/home/jmx/Desktop/javap/Bank/jm.txt");
BufferedReader br = new BufferedReader(fr);
String rline = br.readLine();
while(rline != null)
{
lines.add(rline);
rline = br.readLine();
}
String[] users = new String[lines.size()];
lines.toArray(users);
for(int i = 0; i < users.length; i++)
{
if(logline.equals(users[i]))
{
System.out.println("Matched");
}
}
System.out.println("Login line: " + logline);
System.out.println("Text Line: " + users[0]);
br.close();
fr.close();
}
}
I've tried to execute your code and everything worked as expected. I received "matched". Maybe it's some kind of encoding issue. Try to compare length and if it is ok, try to leave only one line in the file and try this code:
String logline = "JMX^1234";
ArrayList<String> lines = new ArrayList<String>();
FileReader fr = new FileReader("/home/jmx/Desktop/javap/Bank/jm.txt");
BufferedReader br = new BufferedReader(fr);
String rline = br.readLine();
while(rline != null)
{
lines.add(rline);
rline = br.readLine();
}
String[] users = new String[lines.size()];
lines.toArray(users);
for (char ch : users[0].toCharArray()) {
System.out.print((int)ch);
}
System.out.println();
for (char ch : logline.toCharArray()) {
System.out.print((int)ch);
}
System.out.println();
for(int i = 0; i < users.length; i++)
{
if(logline.equals(users[i]))
{
System.out.println("Matched");
}
}
System.out.println("Login line: " + logline);
System.out.println("Text Line: " + users[0]);
br.close();
fr.close();
It should return equal lines of numbers like this:
7477889449505152
7477889449505152
Matched
Login line: JMX^1234
Text Line: JMX^1234
Also try to check out this answer: https://stackoverflow.com/a/4210732/6226118

Find string inside of the text file. Then getting the following line and need to Split by Index of and substring

Find string inside of a text file. Then get the following line and split by indexOf() and substring().
import java.util.*;
import java.io.*;
public class FileReadTest {
public static void main(String[] args) throws IOException {
File f = new File("a.dat");
Scanner fin = new Scanner(f);
String airportcode = "HOI";
while (fin.hasNextLine()) {
String line = fin.nextLine();
int firstindex = line.indexOf(airportcode);
if (firstindex > 0) {
int Code = line.indexOf("|");
int Country = line.lastIndexOf("|",Code);
int State = line.indexOf("|", Country);
int City = line.indexOf("|", State);
int Airport = line.indexOf("|", City);
System.out.println(Code);
System.out.println(Country);
System.out.println(State);
System.out.println(City);
System.out.println(Airport);
System.out.println(line.substring(0, Code));
break;
}
}
fin.close();
}
}
The 1 sout looks like this:
French Polynesia|HOI|Hao|Tuamotos|Hao Airport
I need using only indexOf() and substring(),
but I need it like this:
French Polynesia
HOI
Hao
Tuamotos
Hao Airport
What should I do?
Starting from the assumption you always the same number of fields, in your case 5 separated by the character | you can solve the problem without using String split method but just indexOf and substring like below:
String s = "French Polynesia|HOI|Hao|Tuamotos|Hao Airport";
for (int i = 0; i < 4; ++i) {
int endIndex = s.indexOf("|");
System.out.println(s.substring(0, endIndex));
s = s.substring(endIndex + 1);
}
System.out.println(s);
The code will print all the fields that can be assigned to your distinct variables.
Assuming that:
file content has lines with the following structure: French Polynesia|HOI|Hao|Tuamotos|Hao Airport
you need to print only those lines that contain "HOI" string
you have to use indexOf and substring only.
Here is code snippet that should work for you (file a.dat is located in resources folder):
package example;
import java.util.*; // for Scanner
import java.io.*; // for File and IOException
public class FileReadTest {
public static void main(String[] args) throws IOException {
File f = new File(
Objects.requireNonNull(FileReadTest.class.getClassLoader().getResource("a.dat")).getFile()
);
Scanner fin = new Scanner(f);
String airportcode = "HOI";
while (fin.hasNextLine()) {
String line = fin.nextLine();
if (line.indexOf(airportcode) != -1) {
int firstindex;
while ((firstindex = line.indexOf("|")) != -1) {
System.out.println(line.substring(0, firstindex));
line = line.substring(firstindex + 1);
}
System.out.println(line); // last data
}
}
}
}

How to read values in a text document and then make then parse them to ints in JAVA

I'm trying to read lines of a text document and take the average of the numbers. My plan was to first read ALL the data in the text file. Then split the string up into a String array, then parse each index into an int array. This is my code up to the point of reading the document.
My Text Doc:
3, 7, 24, 66,
10, 50, 20, 40,
100, 20, 69, 911,
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Testing
{
public static void main(String[] args) throws IOException
{
try
{
String path;
path = "TestNumbers.txt";
File f = new File(path);
FileReader re = new FileReader(f);
BufferedReader in = new BufferedReader(re);
String line = "";
String store = "";
while((line = in.readLine()) != null)
{
store = store + line;
}
System.out.println(store);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Output: 3, 7, 24, 66, 10, 50, 20, 40,100, 20, 69, 911,
In a perfect world I want the values to be separated by either "," or " ".
I tried modifying the store = store + line + " "; but this failed because it would iterate the space even when readLine() was on a blank line.
I can traverse the arrays to parse the int and take the average, but setting up this string to be split is stumping me. I tried String.replace(), String.trim(), and another one that failed me. This isn't homework, I'm in highschool AP CS and this is my own independent study.
Thanks everyone for the help, you all showed plenty of ways to do it. Ended up going with .replace, and made the " " into "". Then just split via the commas. I do want to try out that regex thing though. Thanks everyone again.
The other two solutions may be already what you need, however here is a more idiomatic approach which handles edge cases properly:
{
String path = "TestNumbers.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
builder.append(line);
String[] split = builder.toString().split("\\D+");
int[] numbers = new int[split.length];
for (int i = 0; i < split.length; i++ )
numbers[i] = Integer.parseInt(split[i]);
// 'numbers' now stores every digit segment there is in your string.
} catch(IOException e) {
e.printStackTrace();
}
}
Notable:
Declare BufferedReader as Closeable in a try-with-resources scope.
Do not concatenate Strings in a loop, use StringBuilder instead.
Split to \D+ to remove all non-digits, obtaining digit segments as elements in the final array instead.
Scary Wombat mentioned how to handle blank lines.
You could do a .replace to swap all " " chars for "," chars. If you expect both like ", " in some cases you could even .replace those into just "," first. These are basically tricks.
You could look at String.split(regex) since the regex could be a pattern like "[, ]+" to take any number of spaces and/or commas between numbers as a separator.
Here's a quick demo I tested (skipping the file input, since you seem to have that figured out):
public class tmp {
public static void main(String[] args) {
String input = "1,2, 3, 4\n5, 6, 7\n\n,8"; //what we would read from file
input = input.replace("\n"," "); //simulate removing newlines, ignore this
String[] items = input.split("[, ]+"); //regex split
for(String one : items) {
System.out.println(one);
}
}
}
Something like this?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Testing
{
public static void main(String[] args) throws IOException
{
try
{
//open a file
String path;
path = "TestNumbers.txt";
File f = new File(path);
FileReader re = new FileReader(f);
BufferedReader in = new BufferedReader(re);
String line = ""; //reads a line
String store = ""; //combines all the lines
while((line = in.readLine()) != null) //for each line
{
if(line.length() > 0){ //only add to store if the line contains something
store = store + line + " ";
}
}
//create the string array
String[] finalString = store.split(", ");
//and the integer array to hold the numbers
int [] intArray = new int [finalString.length];
//parse the string array and put each index to the integer array
for (int i = 0; i < finalString.length; i++){
intArray[i] = Integer.parseInt(finalString[i]);
}
//simply calculating the average
//summing up
int sum = 0;
for (int i = 0; i < intArray.length; i++){
sum = sum + intArray[i];
}
//printing the average
System.out.println("Average: " + sum / intArray.length);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}

Reading a file in Java

I have the following code to open and read a file. I'm having trouble figuring out how I can have it go through and print the total number of each character in the file, print the first and last character, and print the character exactly in the middle of the file. What's the most efficient way to do this?
This is the main class:
import java.io.IOException;
public class fileData {
public static void main(String[ ] args) throws IOException {
String file_name = "/Users/JDB/NetBeansProjects/Program/src/1200.dna";
try {
ReadFile file = new ReadFile(file_name);
String[] arrayLines = file.OpenFile();
int i;
for (i=0; i<arrayLines.length; i++)
{
System.out.println(arrayLines[i]);
}
}
catch (IOException e) {
System.out.println(e.getMessage()) ;
}
}
}
and the other class:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private String path;
public ReadFile (String file_path)
{
path = file_path;
}
public String[] OpenFile() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for(i=0; i<numberOfLines; i++)
{
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException
{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine() ) != null)
{
numberOfLines++;
}
bf.close();
return numberOfLines;
}
Some hints which might help.
A Map can be used to store information about each character in the alphabet.
The middle of the file can be found from the size of the file.
These few lines of code will do it (using Apache's FileUtils library):
import org.apache.commons.io.FileUtils;
public static void main(String[] args) throws IOException {
String str = FileUtils.readFileToString(new File("myfile.txt"));
System.out.println("First: " + str.charAt(0));
System.out.println("Last: " + str.charAt(str.length() - 1));
System.out.println("Middle: " + str.charAt(str.length() / 2));
}
Anyone who says "you can't use libraries for homework" isn't being fair - in the real world we always use libraries in preference to reinventing the wheel.
The easiest way to understand I can think of is to read the entire file in as a String. Then use the methods on the String class to get the first, last, and middle character (character at index str.length()/2).
Since you are already reading in the file a line at a time, you can use a StringBuilder to construct a string out of those lines. Using the resulting String, the charAt() and substring() methods you should be able to get out everything you want.

Categories

Resources