String array and txt file - java

I have a problem. I created a application which reads a txt file and splits sentence using the substring function. This is code:
public static void main(String[] args) throws IOException {
String linia = "";
Ob parser = new Ob();
try{
FileReader fr = new FileReader("C:/Dane.txt");
BufferedReader bfr = new BufferedReader(fr);
linia = bfr.readLine();
parser.spl(linia);
} catch( IOException ex ){
System.out.println("Error with: "+ex);
}
}
public class Ob {
String a,b;
public void spl(String linia)
{
a = linia.substring(14, 22);
b = linia.substring(25, 34);
System.out.println(a);
System.out.println(b);
}
}
That works properly, but I want to extend this application. I want to read every line of the text file and save the lines in a String array. I then want to pass every line from the array into my spl function. How can I do that?

Instead, you can do
while((linia = bfr.readLine()) != null) {
parser.spl(linia);
}
and close the reader once done reading all the lines.

Just loop until readLine is null.

You can use something like that:
String linia = null;
while(linia = bfr.readLine() != null){
String a = linia.substring(14, 22);
String b = linia.substring(25, 34);
System.out.println(a);
System.out.println(b);
}

Related

How to Toggle/Switch the Case of every letter in a text file?

Ok so here is the code I created for the program to read a text file.
Now can someone tell me how to switch every letter's case from uppercase to lower and vice versa in the result? Notice that I want the program to read the file from the command line and not a string.
If possible I'd like the answer in code :| Thanks
I am very new in Java and could use some help thanks.
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
java.io.File file = new java.io.File("C:\\Users\\Lifeless\\Desktop\\123.txt");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String num = input.nextLine(); //grabs line
System.out.println(num);
}
}
catch (FileNotFoundException e) {
System.err.format("File does not exist \n");
I used a bufferedReader and put all lines of the file in an ArrayList.
static ArrayList<String> lines;
public static void main(String[] args) throws FileNotFoundException, IOException
{
lines = new ArrayList<>();
File f = new File(args[0]);
BufferedReader r = new BufferedReader(new FileReader(f));
String line = r.readLine ();
while(line != null)
{
lines.add(invert(line));
line = r.readLine ();
}
for(String s : lines)
{
System.out.println(s);
}
}
private static String invert(String line)
{
char[] singleChars = line.toCharArray (); //split Line into single Characters
for(int i = 0;i< singleChars.length;i++) //Iterate over every single Character
{
if(Character.isAlphabetic (singleChars[i]))
{
if(Character.isUpperCase (singleChars[i])) //swap Upper to Lower and vice versa
{
singleChars[i] = Character.toLowerCase (singleChars[i]);
}else
{
singleChars[i] = Character.toUpperCase (singleChars[i]);
}
}
}
return new String(singleChars);
}

Java - What is the best way to make a method that reads a file and outputs an array of what the file contains?

I am learning Java and in order to learn more about Java IO I am making a program to read a file path and return an array that contains everything from the file. I didn't want to specify that the data had to be integers so I've been working in strings. I'm running into an issue when I try to run a method returning an array. Is there a better way I should be writing this code?
import java.io.*;
public class OrganizeIO
{
public static void main(String[] args) throws Exception
{
String sampleData[] = readFile("C://Users/Tweak/workspace/FileIO/resources/data.txt");
int i = 0;
while(sampleData[i] != null)
{
System.out.print(sampleData[i]);
i++;
}
}
public static String[] readFile(String file) throws IOException
{
BufferedReader br = null;
String currentLine;
String[] data;
br = new BufferedReader(new FileReader(file));
int i = 0;
while((currentLine = br.readLine()) != null)
{
System.out.println(currentLine);
currentLine = data[i];
i++;
}
return data[];
}
}
You're not storing anything in data, not to mention you haven't even initialized it (which results in a compilation error). You should be using a List anyway, since you don't know how many lines you are going to read beforehand:
List<String> data = new ArrayList<String>();
while ((currentLine = br.readLine()) != null) {
data.add(currentLine);
}
return data.toArray(new String[data.size()]); // or just return the list?
Also, don't forget to close your BufferedReader:
br.close();
Well for one it looks like you while loop should be
while((currentLine = br.readLine()) != null)
{
System.out.println(currentLine);
data[i] = currentLine;
i++;
}
because you are returning nothing
I think you can work with the class Scanner to read the file and store it in a List.
// Open the file
Scanner scanner = new Scanner(new File("C:\\Users\\Tweak\\workspace\\FileIO\\resources\\data.txt"));
// Read the file line by line
List<String> result = new ArrayList<String>();
while (scanner.hasNext())
{
result.add(scanner.nextLine());
}
scanner.close();
// If you want an array
String sampleData[] = result.toArray(new String[result.size()]);
Since you don't know how many lines you get, storing the read lines directly in an array is inappropriate, better take a List implementation for that:
public static List<String> readFile (File file, String encoding) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
List<String> result = new LinkedList<String>();
String line;
while ((line = reader.readLine()) != null) {
result.add(line);
}
return result;
}
Usage:
public static void main (String[] args) throws IOException {
File file = new File("C://Users/Tweak/workspace/FileIO/resources/data.txt");
List<String> lines = readFile(file, "UTF-8");
for (String line : lines) {
System.out.println(line);
}
}
You can of course convert the List into a String array later, if that's what you want:
String[] linesArray = lines.toArray(new String[0]);

Java: adding to a string array in a while loop using a file reader

I have been making a little program that needs to read a list of golf courses that could be changeing and needs to be called when ever. Here is the code:
public class Courses {
public String[] courselist;
public void loadCourses() throws IOException{
int count = 0;
int counter = 0;
File f = new File("src//courses//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
while(count<1){
String s = reader.readLine();
if(s.equalsIgnoreCase("*stop*")){
reader.close();
count = 5;
}else{
courselist[counter] = s;
counter++;
}
s = "";
}
}
}
And now this is what is in the txt file.
RiverChase
Steward Peninsula
Lake Park
Coyote Ridge
*stop*
Now when ever i start to run the program because i call the method instantly it gives me a throw exeption and it is because of the array. And i need to stay and array because i use it in a JComboBox. If you can help or fix the problem. Most likely im just doing it wrong, im a noob. Just help. Thanks in advance.
I know all the file reader and stuff works because it prints out to the system correct, i just need help writing it to the array repetedly.
You should initialize your array before using it
public static final MAX_SIZE = 100;
public String[] courselist = new String[MAX_SIZE];
Change your code to assign a new array during loadCourses(), and add a call to loadCourses() to your constructor:
public class Courses {
public String[] courselist;
public Courses() throws IOException { // <-- Added constructor
loadCourses(); // <-- Added call to loadCourses
}
public void loadCourses() throws IOException {
int count = 0;
int counter = 0;
File f = new File("src//courses//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
List<String> courses = new ArrayList<String>(); // <-- A List can grow
while(true){
String s = reader.readLine();
if (s.equalsIgnoreCase("*stop*")){
break;
}
courses.add(s);
}
courseList = courses.toArray(new String[0]); // <-- assign it here
}
}
This ensures that when you create an instance, it starts out life with the array initialised. Not only will you not get an error, but the data will always be correct (unlike other answers that simply create an empty (ie useless) array.
Note that this code will work with any number of course names in the file (not just 5).
You'd better create a List that is easier to manipulate and convert it as an array at the end of the process :
List<String> list = new ArrayList<String>();
String [] array = list.toArray(new String [] {});
Here is a possible implementation of the loading using a List :
public static String [] loadCourses() throws IOException {
File f = new File("src//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
List<String> courses = new ArrayList<String>();
while (true){
String s = reader.readLine();
if (s == null || s.trim().equalsIgnoreCase("*stop*")){
break;
} else{
courses.add(s);
}
}
return courses.toArray(new String [] {});
}
Also why use a stop keyword ? You could simply stop the process when you reach the end of the file (when s is null).
Here some example, without using the *stop*:
public class ReadFile {
public static void main(String[] args) {
BufferedReader reader = null;
List<String> coursesList = new ArrayList<>();
String[] courses;
try {
File file = new File("courses.txt");
reader = new BufferedReader(new FileReader(file));
String readLine;
do {
readLine = reader.readLine();
if(readLine == null)
break;
coursesList.add(readLine);
} while (true);
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
courses = coursesList.toArray(new String[coursesList.size()]);
for(int i = 0; i < courses.length; i++) {
System.out.println(courses[i]);
}
}
}

How to read in a txt file

I'm trying to read in from whats on the first two lines of a txt file, put it on a string and pass that string onto my methods. I'm confused on what I need to do in the main method.
Heres what I have:
public class TestingClass {
Stacked s;// = new Stacked(100);
String Finame;
public TestingClass(Stacked stack) {
//Stacked s = new Stacked(100);
s = stack;
getFileName();
readFileContents();
}
public void readFileContents() {
boolean looping;
DataInputStream in;
String line = "" ;
int j, len;
char ch;
try {
in = new DataInputStream(new FileInputStream(Finame));
len = line.length();
for(j = 0; j<len; j++) {
System.out.println("line["+j+"] = "+line.charAt(j));
}
}
catch(IOException e) {
System.out.println("error " + e);
}
}
public void getFileName() {
Scanner in = new Scanner(System.in);
System.out.println("Enter File Name");
Finame = in.nextLine();
System.out.println("You Entered " + Finame);
}
public static void main(String[] args) {
Stacked st = new Stacked(100);
TestingClass clas = new TestingClass(st);
//String y = new String("(z * j)/(b * 8) ^2");
// clas.test(y);
}
I tried String x = new String(x.getNewFile()) I'm not sure if thats the right way to go with that or not.
Try this:
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line1 = reader.readLine();
String line2 = reader.readLine();
It's even easier in Java 1.5+. Use the Scanner class. Here's an example. Essentially, it boils down to:
import java.io.*;
import java.util.Scanner;
public static void main(String... aArgs) throws FileNotFoundException {
String fileName = "MYFILE HERE";
String line = "";
Scanner scanner = new Scanner(new FileReader(fileName));
try {
//first use a Scanner to get each line
while ( scanner.hasNextLine() ){
line = scanner.nextLine();
}
}
finally {
//ensure the underlying stream is always closed
//this only has any effect if the item passed to the Scanner
//constructor implements Closeable (which it does in this case).
scanner.close();
}
}
...so there's really no reason for you to have a getFileContents() method. Just use Scanner.
Also, the entire program flow could use some restructuring.
Don't declare a Stacked inside of your main method. It's likely
that's what your testing class should encapsulate.
Instead, write a private static String method to read the file name from the keyboard, then pass that to to your TestingClass object.
Your TestingClass constructor should call a private method that opens
that file, and reads in the first 2 (or however many else you end up
wanting) lines into private class variables.
Afterwards you can instantiate a new Stacked class.
For good encapsulation principles, have your TestClass provide public methods that the Driver program (the class with the public static void main() method can call to access the Stacked instance data without allowing access to the Stacked object directly (hence violating the Law of Demeter).
Likely this advice will seem a little hazy right now, but get in the habit of doing this and in time you'll find yourself writing better programs than your peers.
Reading from a txt file is usually pretty straightforward.
You should use a BufferedReader since you want the first two lines only.
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
linecount = 0;
StringBuilder myline = new StringBuilder();
String line = "";
while ( (linecount < 2) && ((line = br.readLine()) != null) ) {
myline.append(line);
linecount++;
}
// now you have two lines in myline. close readers/streams etc
return myline.toString();
You should change your method signature to return the string. Now, you can say
String x = clas.getFileContent();
//-------------------------------------------------------------------------
//read in local file:
String content = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(mVideoXmlPath));
do {
String line;
line = reader.readLine();
if (line == null) {
break;
}
content += line;
}
while (true);
}
catch (Exception e) {
e.printStackTrace();
}
check this :=)

Find a specific line of a text file (not by line_number) and store it as a new String

I am trying to read a text file in java using FileReader and BufferedReader classes. Following an online tutorial I made two classes, one called ReadFile and one FileData.
Then I tried to extract a small part of the text file (i.e. between lines "ENTITIES" and "ENDSEC"). Finally l would like to tell the program to find a specific line between the above-mentioned and store it as an Xvalue, which I could use later.
I am really struggling to figure out how to do the last part...any help would be very much apprciated!
//FileData Class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main (String[] args) throws IOException {
String file_name = "C:/Point.txt";
try {
ReadFile file = new ReadFile (file_name);
String[] aryLines = file.OpenFile();
int i;
for ( i=0; i < aryLines.length; i++ ) {
System.out.println( aryLines[ i ] ) ;
}
}
catch (IOException e) {
System.out.println(e.getMessage() );
}
}
}
// ReadFile Class
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.lang.String;
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];
String nextline = "";
int i;
// String Xvalue;
for (i=0; i < numberOfLines; i++) {
String oneline = textReader.readLine();
int j = 0;
if (oneline.equals("ENTITIES")) {
nextline = oneline;
System.out.println(oneline);
while (!nextline.equals("ENDSEC")) {
nextline = textReader.readLine();
textData[j] = nextline;
// xvalue = ..........
j = j + 1;
i = i+1;
}
}
//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;
}
}
I don't know what line you are specifically looking for but here are a few methods you might want to use to do such operation:
private static String START_LINE = "ENTITIES";
private static String END_LINE = "ENDSEC";
public static List<String> getSpecificLines(Srting filename) throws IOException{
List<String> specificLines = new LinkedList<String>();
Scanner sc = null;
try {
boolean foundStartLine = false;
boolean foundEndLine = false;
sc = new Scanner(new BufferedReader(new FileReader(filename)));
while (!foundEndLine && sc.hasNext()) {
String line = sc.nextLine();
foundStartLine = foundStartLine || line.equals(START_LINE);
foundEndLine = foundEndLine || line.equals(END_LINE);
if(foundStartLine && !foundEndLine){
specificLines.add(line);
}
}
} finally {
if (sc != null) {
sc.close();
}
}
return specificLines;
}
public static String getSpecificLine(List<String> specificLines){
for(String line : specificLines){
if(isSpecific(line)){
return line;
}
}
return null;
}
public static boolean isSpecific(String line){
// What makes the String special??
}
When I get it right you want to store every line between ENTITIES and ENDSEC?
If yes you could simply define a StringBuffer and append everything which is in between these to keywords.
// This could you would put outside the while loop
StringBuffer xValues = new StringBuffer();
// This would be in the while loop and you append all the lines in the buffer
xValues.append(nextline);
If you want to store more specific data in between these to keywords then you probably need to work with Regular Expressions and get out the data you need and put it into a designed DataStructure (A class you've defined by our own).
And btw. I think you could read the file much easier with the following code:
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
...
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
Then you don't have to read first how many lines the file has. You just start reading till the end :).
EDIT:
I still don't know if I understand that right. So if ENTITIES POINT 10 1333.888 20 333.5555 ENDSEC is one line then you could work with the split(" ") Method.
Let me explain with an example:
String line = "";
String[] parts = line.split(" ");
float xValue = parts[2]; // would store 10
float yValue = parts[3]; // would store 1333.888
float zValue = parts[4]; // would store 20
float ... = parts[5]; // would store 333.5555
EDIT2:
Or is every point (x, y, ..) on another line?!
So the file content is like that:
ENTITIES POINT
10
1333.888 // <-- you want this one as xValue
20
333.5555 // <-- and this one as yvalue?
ENDSEC
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
// read next line
line = reader.readLine();
if(line.equals("10") {
// read next line to get the value
line = reader.readLine(); // read next line to get the value
float xValue = Float.parseFloat(line);
}
line = reader.readLine();
if(line.equals("20") {
// read next line to get the value
line = reader.readLine();
float yValue = Float.parseFloaT(line);
}
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
If you have several ENTITIES in the file you need to create a class which stores the xValue, yValue or you could use the Point class. Then you would create an ArrayList of these Points and just append them..

Categories