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 :=)
Related
im trying to write a class where it would take a text file,reverse its contents and write it back. The way i want to do it is to write the lines in a String[] array,reverse the lines and then write the text back to the text file. Problem is, when I start writing to the String array, it writes off only nulls and i know the text file is not empty. Im using a copy of the BufferedReader to read the lines. I can't seem to understand where am i wrong. When I initialize the String array textFile like down in the code, i have no problems reversing, but when i use the
String[] textFile = new String[getNumberOfLines ()];
method, it doesnt work.
public void reverse() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(WORK_FOLDER_LOCATION + FILE_NAME));
String[] textFile = new String[3];
try {
for (int i = 0; i < textFile.length; i++) {
textFile[i] = reader.readLine();
textFile[i] = reverseLine(textFile[i]);
}
} catch (IOException e) {
throw new IOException("There was a problem while operating with the reader.");
} finally {
reader.close();
}
writeReverseText(textFile);
}
private int getNumberOfLines(BufferedReader reader) throws IOException {
BufferedReader linesReader = reader;
int counter = 0;
try {
while (linesReader.readLine() != null) {
counter++;
}
linesReader.close();
} catch (IOException e) {
throw new IOException("There was a problem while counting the lines");
}
return counter;
}
private String reverseLine(String string) {
StringBuilder reversedString = new StringBuilder(string).reverse();
System.out.println(reversedString);
return reversedString.toString();
}
private void writeReverseText(String[] textFile) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(WORK_FOLDER_LOCATION + FILE_NAME));
for (int i = 0; i < textFile.length; i++) {
writer.append(textFile[i]);
writer.append(System.lineSeparator());
}
writer.close();
}
EDIT I managed to solve the issue but changing the getNumberOfLines() method:
private int getNumberOfLines() throws IOException {
BufferedReader linesReader = new BufferedReader(new FileReader(WORK_FOLDER_LOCATION + FILE_NAME));
Hope this helps to the others, i would love to know why the previous code didn't work.
Your getNumberOfLines() method will read all the data from the BufferedReader - so unless you start reading the file again, there's nothing to read, and the very first call to readLine() will return null.
However, instead of doing this, you'd be better off just reading the file once, and populating a List<String>. For example:
List<String> lines = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
lines.add(reverseLine(line));
}
I have a file that contain 100 line
each line contain one tag
I need to obtain the tag value given its rank which is the "id" of TagVertex Class
public abstract class Vertex <T>{
String vertexId ;// example Tag1
T vertexValue ;
public abstract T computeVertexValue();
}
public class TagVertex extends Vertex<String> {
#Override
public String computeVertexValue() {
// How to get the String from my file?
return null;
}
T try this but it doesnt work
public static void main(String args[]) {
File source //
int i=90;
int j=0;
String s = null;
try {
Scanner scanner = new Scanner(source);
while (scanner.hasNextLine()) {
if (j==i) s= scanner.nextLine();
else j++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(s);
}}
Although there is a way to skip characters with BufferedReader, I don't think there's is a built-in way to skip whole lines.
BufferedReader bf = new BufferedReader(new FileReader("MyFile.txt"));
for(int i = 1; i < myVertex.vertexId; i++){
bf.readLine();
}
String n = bf.readLine();
if(n != null){
System.out.println(n);
}
I think there may be a better idea though.
This is command u can use to read from file:
BufferedReader bf = new BufferedReader(new FileReader("filename"));
This will read the file to the buffer.
Now, for reading each line u should use a while loop and read each line into string.
Like:
String str;
while((str = bf.readLine()) != null){
//handle each line untill the end of file which will be null and quit the loop
}
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]);
}
}
}
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);
}
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..