Remove spaces only certain places not everywhere - java

I am taking in txt from a txt file and trying to store it in an arraylist. In the txt file the which mean ballot are not together instead the teacher placed it on a separate line. So we have to get all of the ballots together but i am not able to get them to be all together she placed the first ballot on the line like in example below. And we have to make the rest of them together. I am using a fileinputstream to collect the txt from the textfile.
the text looks like this :
person 1
person 2
person 3
<b> 1 2 3
<b>
1
3
2
I want it to look like this
person 1
person 2
person 3
<b> 1 2 3
<b> 1 3 2
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter file name: ");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.next();
File file = new File(fileName);
ArrayList<String> ballot;
ballot = new ArrayList<String>();
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream ds = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(ds));
// Pattern p;
// Matcher m;
String strLine;
String inputText = "";
String newline = System.getProperty("line.separator");
while ((strLine = br.readLine()) != null) {
ballot.add(strLine);
}

You need to use a StringBuilder sb = new StringBuilder();. Each time you have a token String t, call sb.append(t.trim()).append(' ');. When done with parsing your file, call sb.toString();. If you want to add newlines here and there, use sb.append('\n');.
If you want an array of your tokens, you should use an ArrayList<String> al = new ArrayList<String>; Each time you have a set of token s making a line, use al.add(s); When done, call String[] result = al.toArray(new String[al.length]); You will need to concatenate your set of tokens into s for each line.

Related

Retrieving variables from a text file through a hashmap

I am creating a school program for a project in which I a writing words and translations to a file, (separated by a character). I have read that I can read them via a hash map into an array. I was just wondering if someone could point me in the right direction as how to do this.
If anyone has a better idea of how to store and retrieve the words I would love to learn. The reason I am writing to a file is so the user can store as many words as they want.
Thank-you so much :D
You can use java.util.HashMap to store user words and related translations:
String userWord = null;
String translation = null, translation1 = null;
Map<String, String[]> map = new HashMap();
map.put(userWord, new String[] { translation, translation1 });
String[] translations = map.get(userWord);
This map lets you map single userWord to multiple translations.
Here's a reference for learning how to use BufferedReader: BufferedReader
Here's a reference for learning how to use FileReader: FileReader
import java.io.*;
class YourClass
{
public static void main() throws IOException
{
File f = new File("FilePath"); // Replace every '\' with '/' in the file path
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = "";
String FileString = "";
while((line = br.readLine()) != null)
{
// Now 'line' contains each line of the file
// If you want, you can store the entire file in a String, like this:
FileString += line + "\n"; // '\n' to register each new line
}
System.out.println(FileString);
}
} // End of class
I'm still a newbie, and don't understand much about HashMap, but I can tell you how to store it in a String array:
FileString = FileString.replaceAll("\\s+", " ");
String[] Words = FileString.split(" ");
FileString.replaceAll("\\s+", " ") - Replaces 1 or more spaces with 1 space, so as to avoid any logical errors.
FileString.split(" ") - Returns a String array of each String separated by a space.
You can try something like this
File f = new File("/Desktop/Codes/Text.txt");
// enter your file location
HashMap<String, String[]> hs = new HashMap<String, String[]>();
// throw exception in main method
Scanner sc = new Scanner(f);
String s="";
while(sc.hasNext()){
s = sc.next();
// create a method to search translation
String []trans = searchTrans(s);
hs.put(s, trans);
}

Read from file with BufferedReader

Basically I've got an assignment which reads multiple lines from a .txt file.
There are 4 values in the text file per line and each value is separated by 2 spaces.
There are about 10 lines of data in the file.
After taking the input from the file the program then puts it onto a Database. The database connection functionality works fine.
My issue now is with reading from the file using a BufferedReader.
The issue is that if I uncomment any 1 of the 3 lines at the bottom the BufferedReader reads every other line. And if I don't use them then there's an exception as the next input is of type String.
I have contemplated using a Scanner with the .hasNextLine() method.
Any thoughts on what could be the problem and how to fix it?
Thanks.
File file = new File(FILE_INPUT_NAME);
FileReader fr = new FileReader(file);
BufferedReader readFile = new BufferedReader(fr);
String line = null;
while ((line = readFile.readLine()) != null) {
String[] split = line.split(" ", 4);
String id = split[0];
nameFromFile = split[1];
String year = split[2];
String mark = split[3];
idFromFile = Integer.parseInt(id);
yearOfStudyFromFile = Integer.parseInt(year);
markFromFile = Integer.parseInt(mark);
//line = readFile.readLine();
//readFile.readLine();
//System.out.println(readFile.readLine());
}
Edit: There was an error in the formatting of the .txt file. a missing value.
But now I get an ArrayOutOfBoundsException.
Edit edit: Another error in the .txt file! Turns out there was a single space instead of a double. It seems to be working now. But any advice on how to deal with file errors like this in the future?
The issue is that if I uncomment any 1 of the 3 lines at the bottom the BufferedReader reads every other line.
Correct. If you put any of those lines of code in, the line of text read will be thrown away and not processed. You're already reading in the while condition. You don't need another read. If you put any of those lines in, they will be thrown away and not proce
A compilable version of the code posted could be
public void read() throws IOException {
File file = new File(FILE_INPUT_NAME);
FileReader fr = new FileReader(file);
BufferedReader readFile = new BufferedReader(fr);
String line;
while ((line = readFile.readLine()) != null) {
String[] split = line.split(" ", 4);
if (split.length != 4) { // Not enough tokens (e.g., empty line) read
continue;
}
String id = split[0];
String nameFromFile = split[1];
String year = split[2];
String mark = split[3];
int idFromFile = Integer.parseInt(id);
int yearOfStudyFromFile = Integer.parseInt(year);
int markFromFile = Integer.parseInt(mark);
//line = readFile.readLine();
//readFile.readLine();
//System.out.println(readFile.readLine());
}
}
The above uses a single space (" " instead of the original " "). To split on any number of changes, a regular expression can be used, e.g. "\\s+". Of course, exactly 2 spaces can also be used, if that reflects the structure of the input data.
What the method should do with the extracted values (e.g., returning them in an object of some type, or saving them to a database directly), is up to the application using it.

Scanning, spliting and assigning values from a text file

I'm having trouble scanning a given file for certain words and assigning them to variables, so far I've chosen to use Scanner over BufferedReader because It's more familiar. I'm given a text file and this particular part I'm trying to read the first two words of each line (potentially unlimited lines) and maybe add them to an array of sorts. This is what I have:
File file = new File("example.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] ary = line.split(",");
I know It' a fair distance off, however I'm new to coding and cannot get past this wall...
An example input would be...
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
...
and the proposed output
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
...
You can try something like this
File file = new File("D:\\test.txt");
Scanner sc = new Scanner(file);
List<String> list =new ArrayList<>();
int i=0;
while (sc.hasNextLine()) {
list.add(sc.nextLine().split(",",2)[0]);
i++;
}
char point='A';
for(String str:list){
System.out.println("Variable"+point+" = "+str);
point++;
}
My input:
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
Out put:
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
To rephrase, you are looking to read the first 2 words of a line (everything before the first comma) and store it in a variable to process further.
To do so, your current code looks fine, however, when you grab the line's data, use the substring function in conjunction with indexOf to just get the first part of the String before the comma. After that, you can do whatever processing you want to do with it.
In your current code, ary[0] should give you the first 2 words.
public static void main(String[] args)
{
File file = new File("example.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
List l = new ArrayList();
while ((line = br.readLine()) != null) {
System.out.println(line);
line = line.trim(); // remove unwanted characters at the end of line
String[] arr = line.split(",");
String[] ary = arr[0].split(" ");
String firstTwoWords[] = new String[2];
firstTwoWords[0] = ary[0];
firstTwoWords[1] = ary[1];
l.add(firstTwoWords);
}
Iterator it = l.iterator();
while (it.hasNext()) {
String firstTwoWords[] = (String[]) it.next();
System.out.println(firstTwoWords[0] + " " + firstTwoWords[1]);
}
}

Reading each line of different data types from text file

I have a text file that provides information for 22 golf courses, including name of course, name, location, designer, greens fee, par, year built, and total yards. As I read in, each line needs to be stored to the appropriate variable and then used to create a few objects. The first line of the file is the number of golf courses in the text file.
FileInputStream fstream = new FileInputStream(System.getProperty("user.dir")
+ "\\GolfCourses.txt");
//use file
DataInputStream in = new DataInputStream(fstream);
//read input
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Tree newTree = new Tree();
try{
String line = br.readLine();
if(line==null)
throw new IOException();
int clubs = Integer.parseInt(line);
for(int i = 0; i < clubs; i++){
String name = br.readLine();
String location = br.readLine();
double fee = Double.parseDouble(br.readLine());
int par = Integer.parseInt(br.readLine());
String designer = br.readLine();
int built = Integer.parseInt(br.readLine());
int yards = Integer.parseInt(br.readLine());
newTree.insert(new TreeNode(new GolfCourse(name, location, designer, fee, par, built, yards)));
}
in.close();
}catch(IOException e){
System.out.println(e);
}
The read-in seems to jump ahead of itself, so the program is trying to parse strings instead of numbers. I've never had this problem before so I'm lost on how to fix it.
EDIT: The code is now working as intended. The issue was coming from the "i <= clubs" piece of the for loop. Thank you for taking the time to help!
It's because your first br.readLine() would get your first line from the file, which is number of clubs. After the if statement, which fails, you are calling br.readLine(). This call would get the next line, as the first line was already retrived in the last call to br.realLine() in the if statement.
Try this:
String line = br.readLine();
if(line == null) {
throw new IOException();
}
int clubs = Integer.parseInt(line);
Read the file like this:
File f = new File("Path");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
Retriving of Fields:
If the fields like golf courses, name, locations are on a single line separated by "single space" for each entry:
- Use split(" ");
If the fields like golf courses, name, locations one per each line:
- Use split("\n"); Not "\\" but "\"
- Use for-loop with count of 8, so to get 8 fields.
Creation of Object:
- Create a Java bean with 8 fields, to hold these values.

Text processing in java android

I have a file that looks similar to this
12345 one
12345 two
12345 three
.......
Question is how can i get all of the values from second row and store them in a String[]
i know how to read file in java just dont know how to cut the second row
1. Store Each line from the file into an ArrayList<String>, its more flexible than String[] array.
2. Then access the line you need by get() method of ArrayList
Eg:
ArraList<String> arr = new ArrayList<String>();
//Now add each lines into this arr ArrayList
arr.get(1); // Getting the Second Line from the file
`
You can split the file line by new line.
String [] names = fileString.split("\n");
Ok this is what i did but it skips first line
FileInputStream fstream = new FileInputStream("/sys..........");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
strLine = br.readLine();
while ((strLine = br.readLine()) != null) {
delims = strLine.split(" ");
first = delims[1];
where.add(first);
}
in.close();
From example above it contains only "two" and "three"

Categories