Read from txt file - Save when a line-break occurs - java

I want to read from .txt file, but I want to save each string when an empty line occurs, for instance:
All
Of
This
Is
One
String
But
Here
Is A
Second One
Every word from All to String will be saved as one String, while every word from But and forward will be saved as another. This is my current code:
public static String getFile(String namn) {
String userHomeFolder = System.getProperty("user.home");
String filnamn = userHomeFolder + "/Desktop/" + namn + ".txt";
int counter = 0;
Scanner inFil = new Scanner(new File(filnamn));
while (inFil.hasNext()) {
String fråga = inFil.next();
question.add(fråga);
}
inFil.close();
}
What and how should I adjust it? Currently, it saves each line as a single String. Thanks in advance.

I assume your question is regarding java.
As you can see I changed return type of your method to List because returning single String doesn't make sense when splitting full text into multiple Strings.
I also don't know what question variable so I switched it with allParts being list of sentences separated by empty line(variable part).
public static List<String> getFile(String namn) throws FileNotFoundException {
String userHomeFolder = System.getProperty("user.home");
String filnamn = userHomeFolder + "/Desktop/" + namn + ".txt";
int counter = 0;
// this list will keep all sentence
List<String> allParts = new ArrayList<String>(); s
Scanner inFil = new Scanner(new File(filnamn));
// part keeps single sentence temporarily
String part = "";
while (inFil.hasNextLine()) {
String fråga = inFil.nextLine(); //reads next line
if(!fråga.equals("")) { // if line is not empty then
part += " " + fråga; // add it to current sentence
} else { // else
allParts.add(part); // save current sentence
part = ""; // clear temporary sentence
}
}
inFil.close();
return allParts;
}

Related

How can read a txt file so that all words are placed in a new array element and not every new line is placed in a element?

I currently have written a code that is able to read through a .txt file and for every new line it will be placed in a array element (not very hard). It works but this was not my initial intention, I want to have every word placed in a new array element, not after every new line. Here is my current code, can someone maybe help? Thank you!
public static ArrayList<String> read_file() {
try {
ArrayList<String> data_base = new ArrayList<String>();
Scanner s1 = new Scanner(new File("C:\\Users\\Jcool\\OneDrive\\A Levels\\Computer Science\\CSV files\\data convert\\convert.txt"));
while(s1.hasNextLine()) {
data_base.add(s1.nextLine());
}
return data_base;
}catch(FileNotFoundException e) {
}
return null;
}
Read all the lines at once and split them into array.
private static String readAllBytes(String filePath)
{
String content = "";
try
{
content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
}
catch (IOException e)
{
e.printStackTrace();
}
return content;
}
Create a method named readAllBytes and call it like this;
/* String to split. */
String stringToSplit = readAllBytes(filePath);
String[] tempArray;
/* delimiter */
String delimiter = " ";//space if its a file contains words
/* given string will be split by the argument delimiter provided. */
tempArray = stringToSplit.split(delimiter);
If you mean to split your lines into array check this answer.
Take a look at the split(String) method. It returns a String[]. As an example
String string = "AAA-BBB";
String[] parts = string.split("-");
String part1 = parts[0]; // AAA
String part2 = parts[1]; // BBB

Editing the a specific string in a file?

So I am creating a program which when called, will have input, go to a file and change the number assigned to the string called. For example:
The file would look like:
stone 0 wood 5 water 2 metal 5
and if "wood" was called, it would go into the file, find wood then send add one to the value to the right of wood, which would only change that value to 6, then saves the file.
I've looked around on the internet but couldn't really find much which is tailored to my specific problem. Its either changing an int to either one or the other, or changing all ints to something.
public class Main {
public static void main(String[] args) {
FileWriter fw;
BufferedReader reader;
StringBuffer ib;
String allBlockAndNull = "stone 0 wood 5 water 2 metal 5";
String strDir = "C:\\Users\\amdro\\Desktop\\test.txt";
File fileDir = new File(strDir);
//creates file it doesn't exist
try {
fw = new FileWriter(fileDir);
fw.write(allBlockAndNull);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}finally {}
}
}
If you could expand from the above, that would be great!
This is a very simple and basic solution to your problem: It consists of reading the file, appending all changes to a string and overwriting the same file with the string.
Create a scanner to read your text file and initialise a new string variable
Scanner s = new Scanner(new File("fileName.txt"));
String line = "";
While there is still a character in the text file, get the word and the number
while(sc.hasNext()){
String word = s.next();
int number = s.nextInt();
Then, inside the while loop, use switch and case to check the word. For example, if word = "wood", append "wood" and the new number, newNumber to line
case "wood":
line += word + " " + newNumber + " ";
break;
The default will be appending the word and the old number, number
default:
line += word + " " + number + " ";
Finally, just create a FileWriter and a BufferedWriter to write line to the text file.
You can't add numbers to a value from a file because all the values are Strings but what you can do is replace the String value
public static void main(String[] args) throws IOException {
File file = new File("file.txt");//The file containing stone 0 wood 5 water 2 metal 5
BufferedReader reader = new BufferedReader(new FileReader(file));
String words = "", list = "";
while ((words = reader.readLine()) != null) {
list += words;
}
reader.close();
Scanner s = new Scanner(file);
if(list.contains("wood")) {
String replacedtext = list.replaceAll("wood 5", "wood 6");
FileWriter writer = new FileWriter("file.txt");
writer.write(replacedtext);
writer.close();
}
}
}

In Java, using Scanner, Is there a way to find a specific String in a CSV file, use it as a column header and return all values under it?

I am trying to find the String "5464" in a csv document then have it return all of the values under that String (same number of Delimiters from the start of the line), until reaching the end of the list (no more values in the column). Any help would be sincerely appreciated.
import javax.swing.JOptionPane;
public class SearchNdestroyV2 {
private static Scanner x;
public static void main(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464"
readRecord(searchTerm,filepath);
}
public void readRecord(String searchTerm, String filepath)
{
boolean found = false;
String ID = ""; String ID2 = ""; String ID3 = "";
}
try
{
x = new Scanner(new File(filepath));
x.useDelimeter("[,\n]");
while(x.hasNext() && !found )
{
ID = x.next();
ID2 = x.nextLine();
ID3 = x.nextLine();
if(ID.equals(searchTerm))
{
found = true;
}
}
if (found)
{
JOptionPane.showMessageDialog(null,"ID: " + ID + "ID2: " + ID2 + "ID3: "+ID3);
}
}
else
{
JOptionPane.showMessageDialog(null, "Error:");
}
catch(Exception e)
{
}
{
}
I'm not exactly sure of what you mean. The way I read your question:
You want to locate a specific String ("5464") that is contained within a specific column within a comma (,) delimited CSV file. If this specific string (search term) is found then retrieve all other values contained within the same column for the rest of the CSV file records from the point of location. Here is how:
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class SearchNDestroyV2 {
private Scanner fileInput;
public static void main(String[] args) {
// Do this if you don't want to deal with statics
new SearchNDestroyV2().startApp(args);
}
private void startApp(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464";
readRecord(searchTerm, filepath);
}
public void readRecord(String searchTerm, String filepath) {
try {
fileInput = new Scanner(new File(filepath));
// Variable to hold each file line data read.
String line;
// Used to hold the column index value to
// where the found search term is located.
int foundColumn = -1;
// An ArrayList to hold the column values retrieved from file.
ArrayList<String> columnList = new ArrayList<>();
// Read file to the end...
while(fileInput.hasNextLine()) {
// Read in file - 1 trimmed line per iteration
line = fileInput.nextLine().trim();
//Skip blank lines (if any).
if (line.equals("")) {
continue;
}
// Split the curently read line into a String Array
// based on the comma (,) delimiter
String[] lineParts = line.split("\\s{0,},\\s{0,}"); // Split on any comma/space situation.
// Iterate through the lineParts array to see if any
// delimited portion equals the search term.
for (int i = 0; i < lineParts.length; i++) {
/* This IF statement will always accept the column data and
store it if the foundColumn variable equals i OR the current
column data being checked is equal to the search term.
Initially when declared, foundColumn equals -1* and will
never equal i unless the search term is indeed found. */
if (foundColumn == i || lineParts[i].equals(searchTerm)) {
// Found a match
foundColumn = i; // Hold the Coloumn index number of the found item.
columnList.add(lineParts[i]); // Add the found ite to the List.
break; // Get out of this loop. Don't need it anymore for this line.
}
}
}
if (foundColumn != -1) {
System.out.println("Items Found:" + System.lineSeparator() +
"============");
for (String str : columnList) {
System.out.println(str);
}
}
else {
JOptionPane.showMessageDialog(null, "Can't find the Search Term: " + searchTerm);
}
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
If however, what you want is to search through the CSV file and as soon as any particular column equals the Search Term ("5464") then simply store the CSV line (all its data columns) which contains that Search Term. Here is how:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SearchNDestroyV2 {
/* A JFrame used as Parent for displaying JOptionPane dialogs.
Using 'null' can allow the dialog to open behind other open
applications (like the IDE). This ensures that it will be
displayed above all other applications at center screen. */
JFrame iFRAME = new JFrame();
{
iFRAME.setAlwaysOnTop(true);
iFRAME.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iFRAME.setLocationRelativeTo(null);
}
public static void main(String[] args) {
// Do this if you don't want to deal with statics
new SearchNDestroyV2().startApp(args);
}
private void startApp(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464";
ArrayList<String> recordsFound = readRecord(searchTerm, filepath);
/* Display any records found where a particular column
matches the Search Term. */
if (!recordsFound.isEmpty()) {
System.out.println("Records Found:" + System.lineSeparator()
+ "==============");
for (String str : recordsFound) {
System.out.println(str);
}
}
else {
JOptionPane.showMessageDialog(iFRAME, "Can't find the Search Term: " + searchTerm);
iFRAME.dispose();
}
}
/**
* Returns an ArrayList (of String) of any comma delimited CSV file line
* records which contain any column matching the supplied Search Term.<br>
*
* #param searchTerm (String) The String to search for in all Record
* columns.<br>
*
* #param filepath (String) The CSV (or text) file that contains the data
* records.<br>
*
* #return ({#code ArrayList<String>}) An ArrayList of String Type which
* contains the file line records where any particular column
* matches the supplied Search Term.
*/
public ArrayList<String> readRecord(String searchTerm, String filepath) {
// An ArrayList to hold the line(s) retrieved from file
// that match the search term.
ArrayList<String> linesList = new ArrayList<>();
// Try With Resourses used here to auto-close the Scanner reader.
try (Scanner fileInput = new Scanner(new File(filepath))) {
// Variable to hold each file line data read.
String line;
// Read file to the end...
while (fileInput.hasNextLine()) {
// Read in file - 1 trimmed line per iteration
line = fileInput.nextLine().trim();
//Skip blank lines (if any).
if (line.equals("")) {
continue;
}
// Split the curently read line into a String Array
// based on the comma (,) delimiter
String[] lineParts = line.split("\\s{0,},\\s{0,}"); // Split on any comma/space situation.
// Iterate through the lineParts array to see if any
// delimited portion equals the search term.
for (int i = 0; i < lineParts.length; i++) {
if (lineParts[i].equals(searchTerm)) {
// Found a match
linesList.add(line); // Add the found line to the List.
break; // Get out of this loop. Don't need it anymore for this line.
}
}
}
}
catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
return linesList; // Return the ArrayList
}
}
Please try to note the differences between the two code examples. In particular how the file reader (Scanner object) is closed, etc.

Java - take name from string

I'm developing a Java application that make some statistic stuff.
This application take all data from a .txt file which is supplied by the user.
The first line of that file contains the name of the sets of data that follows like this:
velx,vely,velz
//various data
I need to analyze that first line and retrieve the three name of variables, I correctly get the first two but I'm not able to get the last one.
There the code to get names:
public ArrayList<String> getTitle(){
// the ArrayList originally is not here but in the class intestation
// I copied it here to simplify code's understanding
ArrayList<String> title = new ArrayList<String>();
try {
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
int titleN = 0;
String line = br.readLine(); //read the first line of file
String temp;
System.out.println(ManageTable.class.getName() + " Line: " + line);
int c = line.length();
for(int i = 0; i <c; i++){
if((line.charAt(i) == ',') || **ANOTHER CONDITION** ){
temp = sb.toString();
System.out.println(ManageTable.class.getName() +" Temp is: " + temp);
title.add(temp);
System.out.println(ManageTable.class.getName() + " Title added");
sb.delete(0, sb.length());
}else{
sb.append(line.charAt(i));
}
}
} catch (IOException ex) {
Logger.getLogger(ManageTable.class.getName()).log(Level.SEVERE, null, ex);
}
return title;
}
I need to add a second condition to the if statement in order to find out when the line is ended and save the last name, even if its not followed by ','
I tried using:
if((line.charAt(i) == ',') || (i==c))
but from the name I get, always miss a character.
How can I check the end of the line and so get the full name?
If line contains just three names separated by comma, you can do
String[] names = line.split(",");
No need for all this looping. You can just split the line around the comma to get an array:
String[] names = line.split(",");

Printing the string after a string in a string in java

I have a txt file containing words and their abbreviations that looks like this
one,1
two,2
you,u
probably,prob
...
I have read the txt file into a string splitting it and replacing the commas with spaces like so..
public String shortenWord( String inWord ) {
word = inWord;
String text = "";
try {
Scanner sc = new Scanner(new File("abbreviations.txt"));
while (sc.hasNextLine()) {
text = text + sc.next().replace(",", " ") + " ";
}
// System.out.println(text);
//System.out.println(word);
if (text.contains(word)) {
System.out.println(word);
}
else {
System.out.println("nope");
}
}
catch ( FileNotFoundException e ) {
System.out.println( e );
}
return text;
}
The user must input a word that they want abbreviated and it will return the abbreviated version of the word.
class testit{
public static void main(String[] args){
Shortener sh = new Shortener();
sh.shortenWord("you");
}
}
I have it returning the word they entered if it is found but i want it to return the word next to it in the file which would be the abbreviated version.
eg. printed string 'text' looks like ..
one 1 two 2 three 3 you u probably prob hello lo
I want them to be able to enter 'you' the program find 'you' and then prints 'u' which is the next string over separated by a space
Removing the comma achieves nothing, so don't do it.
I would first split:
String[] text = sc.next().split(",");
Then compare with the first part of the split:
if (text[0].equals(word))
and if true, return the second part of the split:
return text[1];
Part of the logic looks like below:
Map<String,String> myShortHand = new HashMap<String, String>();
Scanner sc = new Scanner(new File("abbreviations.txt"));
while (sc.hasNextLine()) {
String text[] = sc.next().split(",");
myShortHand.put(text[0],text[1]);
}
Now get the details from map like
myShortHand.get("one");

Categories

Resources