Sorry if this question has been asked before, but I'm new to coding and I can't find an answer online because I don't know the theory well enough to know how to describe what I'm looking for.
Basically, I want to know if theres a way I can initialize a variable/macro that I can tie to this long try statement, so instead of writing THIS every time I want to read my file
System.out.println("filler");
System.out.println("filler");
try {
FileReader reader = new FileReader("MyFile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("filler");
System.out.println("filler");
I can just write something like..
System.out.println("filler");
System.out.println("filler");
Read1
System.out.println("filler");
System.out.println("filler");
As #king_nak suggests, use a method.
public void readFile(String path) {
try {
FileReader reader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And then you can do what you wanted:
System.out.println("filler");
readFile("MyFile.txt") // call the method
System.out.println("filler");
In Java, MACROS are called constants instead, and are initialised with the final keyword.
For having a String constant for example:
final String str = "Hello World!";
What you need here, is a good ol' fashioned Java method.
You need to declare it outside your main method, in a class of your choosing. What the following method will do, is that it will read a file and add each line of the file to a list (an ArrayList more specifically).
Each element of the ArrayList is one line of text, read from the file.
Note: This method is quite advanced, since it utilises streams to achieve what was described above. If you use this, then please spend some time to understand it first! Otherwise, I would suggest you don't use this as a beginner. (You can read the documentation for for Reading, Writing and Creating files).
public ArrayList<String> readLines (String filename){
ArrayList<String> lines = null;
// Get lines of text from file as a stream.
try (Stream<String> stream = Files.lines(Paths.get(filename))){
// convert stream to a List-type object
lines = (ArrayList<String>)stream.collect(Collectors.toList());
}
catch (IOException ioe){
System.out.println("Could not read lines of text from the file..");
ioe.printStackTrace();
}
return lines;
}
Then you can use the method like so:
ArrayList<String> lines = null; //Initialise an ArrayList to store lines of text.
System.out.println("filler");
lines = readLines("/path/myFile.txt");
System.out.println(lines.get(0)); //Print the first line of text from list
System.out.println("filler");
lines = readLines("/path/myOtherFile.txt");
for( String str : lines )
System.out.println(str); //Will print every line of text in list
Here is the link for the documentation for java.nio.Files.
Related
Hopefully my explanation does me some justice. I am pretty new to java. I have a text file that looks like this
Java
The Java Tutorials
http://docs.oracle.com/javase/tutorial/
Python
Tutorialspoint Java tutorials
http://www.tutorialspoint.com/python/
Perl
Tutorialspoint Perl tutorials
http://www.tutorialspoint.com/perl/
I have properties for language name, website description, and website url. Right now, I just want to list the information from the text file exactly how it looks, but I need to assign those properties to them.
The problem I am getting is "index 1 is out of bounds for length 1"
try {
BufferedReader in = new BufferedReader(new FileReader("Tutorials.txt"));
while (in.readLine() != null) {
TutorialWebsite tw = new TutorialWebsite();
str = in.readLine();
String[] fields = str.split("\\r?\\n");
tw.setProgramLanguage(fields[0]);
tw.setWebDescription(fields[1]);
tw.setWebURL(fields[2]);
System.out.println(tw);
}
} catch (IOException e) {
e.printStackTrace();
}
I wanted to test something so i removed the new lines and put commas instead and made it str.split(",") which printed it out just fine, but im sure i would get points taken off it i changed the format.
readline returns a "string containing the contents of the line, not including any line-termination characters", so why are you trying to split each line on "\\r?\\n"?
Where is str declared? Why are you reading two lines for each iteration of the loop, and ignoring the first one?
I suggest you start from
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
and work from there.
The first readline gets the language, the second gets the description, and the third gets the url, and then the pattern repeats. There is nothing to stop you using readline three times for each iteration of the while loop.
you can read all the file in a String like this
// try with resources, to make sure BufferedReader is closed safely
try (BufferedReader in = new BufferedReader(new FileReader("Tutorials.txt"))) {
//str will hold all the file contents
StringBuilder str = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
str.append(line);
str.append("\n");
} catch (IOException e) {
e.printStackTrace();
}
Later you can split the string with
String[] fields = str.toString().split("[\\n\\r]+");
Why not try it like this.
allocate a List to hold the TutorialWebsite instances.
use try with resources to open the file, read the lines, and trim any white space.
put the lines in an array
then iterate over the array, filling in the class instance
the print the list.
The loop ensures the array length is a multiple of nFields, discarding any remainder. So if your total lines are not divisible by nFields you will not read the remainder of the file. You would still have to adjust the setters if additional fields were added.
int nFields = 3;
List<TutorialWebsite> list = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new FileReader("tutorials.txt"))) {
String[] lines = in.lines().map(String::trim).toArray(String[]::new);
for (int i = 0; i < (lines.length/nFields)*nFields; i+=nFields) {
TutorialWebsite tw = new TutorialWebsite();
tw.setProgramLanguage(lines[i]);
tw.setWebDescription(lines[i+1]);
tw.setWebURL(lines[i+2]);
list.add(tw);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
list.forEach(System.out::println);
A improvement would be to use a constructor and pass the strings to that when each instance is created.
And remember the file name as specified is relative to the directory in which the program is run.
This question already has answers here:
Modify the content of a file using Java
(6 answers)
Closed 3 years ago.
I am new at java and teacher gave us a project homework. I have to implement read the file line by line, slice the lines at the comma and store the parts at a multidimensional array, change the specific part of the line (I want to change the amount).
The given file:
product1,type,amount
product2,type,amount
product3,type,amount
product4,type,amount
product5,type,amount
I tried this code but I couldn't change the specific part.
BufferedReader reader;
int j=0;
int i=0;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
j++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
String total_length[][]=new String[j][3];
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
String[] item = line.split(",");
total_length[i][0]=item[0];
total_length[i][1]=item[0];
total_length[i][2]=item[0];
i++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Thanks a lot!
First, you need to read the file. There are plenty of way to do it, one of them is:
BufferedReader s = new BufferedReader(new FileReader("filename"));
Which allows you to do s.readLine() to read it line by line.
You can use a while loop to read it until the end. Note that readLine will return null if you reach the end of the file.
Then, for each line, you want to split them with the coma. You can use the split method of Strings:
line.split(",");
Putting it all together, and using a try-catch for IOException, you get:
List<String[]> result = new ArrayList<>();
try (BufferedReader s = new BufferedReader(new FileReader("filename"))) {
String line;
while ((line = s.readLine()) != null) {
result.add(line.split(","));
}
} catch (IOException e) {
// Handle IOExceptions here
}
If you really need a two dimensional array at the end, you can do:
String[][] array = new String[0][0];
array = result.toArray(array);
You then have read the file in the format you wanted, you can now modify the data that you parsed.
I have a file with text in this format:
text:text2:text3
text4:text5:text6
text7:text8:text9
Now what I want to do, is to read the first line, separate the words at the ":", and save the 3 strings into different variables. those variables are then used as parameter for a method, before having the program read the next line and doing the same thing over and over again.. So far I've got this:
public static void main(String[] args) {
BufferedReader reader = null;
try {
File file = new File("C://Users//Patrick//Desktop//textfile.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Also, I've tried this for separation (although not sure Array is the best option:
String[] strArr = sCurrentLine.split("\\:");
Use String[] parts = line.split(":"); to get an array with text, text2 etc. You can then loop through parts and call the method you want with each item in the list.
Your original split does not work, because : is not a special character in Regex. You only have to use an escape character when the split you are trying to achieve uses a special character.
More information here.
I have a text file called "high.txt". I need the data inside for my Android app. But I have absolutely no idea how to read it into an ArrayList of the Strings. I tried the normal way of doing it in Java but apparently that doesn't work in Android since it cant find the file. So how do I go about doing this? I have put it in my res folder. But how do you take the input stream that you get from opening the file within Android and read it into an ArrayList of Strings. I am stuck on that part.
Basically it would look something like this:
3. What do you do for an upcoming test?
L: make sure I know what I'm studying and really review and study for this thing. Its what Im good at. Understand the material really well.
CL: Time to study. I got this, but I really need to make sure I know it,
M: Tests can be tough, but there are tips and tricks. Focus on the important, interesting stuff. Cram in all the little details just to get past this test.
CR: -sigh- I don't like these tests. Hope I've studied enough to pass or maybe do well.
R: Screw the test. I'll study later, day before should be good.
This is for a sample question and all the lines will be stored as separate strings in the array list.
If you put the text file in your assets folder you can use code like this which I've taken and modified from one of my projects:
public static void importData(Context context) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(context.getAssets().open("high.txt")));
String line;
while ((line = br.readLine()) != null) {
String[] columns = line.split(",");
Model model = new Model();
model.date = DateUtil.getCalendar(columns[0], "MM/dd/yyyy");
model.name = columns[1];
dbHelper.insertModel(model);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Within the loop you can do anything you need with the columns, what this example is doing is creating an object from each row and saving it in the database.
For this example the text file would look something like this:
15/04/2013,Bob
03/03/2013,John
21/04/2013,Steve
If you want to read file from External storage than use below method.
public void readFileFromExternal(){
String path = Environment.getExternalStorageDirectory().getPath()
+ "/AppTextFile.txt";
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line, results = "";
while( ( line = reader.readLine() ) != null)
{
results += line;
}
reader.close();
Log.d("FILE","Data in your file : " + results);
} catch (Exception e) {
}
}
//find all files from folder /assets/txt/
String[] elements;
try {
elements = getAssets().list("txt");
} catch (IOException e) {
e.printStackTrace();
}
//for every files read text per line
for (String fileName : elements) {
Log.d("xxx", "File: " + fileName);
try {
InputStream open = getAssets().open("txt/" + fileName);
InputStreamReader inputStreamReader = new InputStreamReader(open);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = "";
while ((line = bufferedReader.readLine()) != null) {
Log.d("xxx", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Here is my code:
try {
String textLine;
FileReader fr = new FileReader("ad.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null) {
textLine = reader.readLine();
jTextArea1.read(reader, "jTextArea1");
}
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
And my .txt file contains the following:
contig00001 length=586 numreads=4
CGGGAAATTATCcGCGCCTTCACCGCCGCCGGTTCCACCGACGAACGGATACTGCGtGaa
ggCCGCGATCCCGTCggaCGGAAAaCGCCcTGGCCCGGGAaCATACCGTTCGGGCCGCCA
AGTGTTATAGCCGGACCACTTGTCAGAACATTTCCaaTCCGAAGATGTGAGTtCGGAAGg
TAAAAGCCCGACAAGTTGCGCGgTGAATTTACCTTtACcGCACGATATGCGTCCGTATTA
AaGAAAaGTTCGAAATTATCAGTAAGGCCGACCTGAAaGCTGACCGGGAGTTCAACAAAA
TCTGCATCACCcGGgTCACGGTCGAAATTGCTGTACGCGGCGCTGAACGTAAATTCACCC
TTTcTAAGGGTGTCGCcGTCGTAAACCGTAAaCAaGCCGGTAGCGCCGCCCATCGGGCCG
CCGGTACCAACCGTCGGTGCCGTGTTTCTtGCATCATTGTCCGATCGAGCGTTCTCGTCC
GCTTGTGCAAaTCCTGCAaTAGCTAACGTGAAAACGATCAGAGCTGTTGTAAATACTCTA
TAAGCGAGATTCATCACATTCCTCcGCCGAAATAAAAAGTTAATTt
contig00002 length=554 numreads=4
TGCGCCAaCCGCGCTCTtCATAAaTGGGCACTGCTCCCGATGGCCgACTCGGGCGGTTCG
CCATGAGATCTTTGCCtACCcAGgAaCtCACcACCAAGTCTGATTGCTGTGTGTTTtCTT
CAAGTCCCTATTTCTATTCtCTTtAATGGAACCCGTAGGAAACCCGTGTAGGACGCGGGA
aCCGCACTTgAAGGGGGAGGCGCGGGGTACCGGtCCGGGAACGTACGGGTACCGGCGGGG
gAGGGGAGGGGGACCgCTCCGGGAAGGCCAGGGGACGGATTGGGGAAGGgCGGGTACCGA
AGCGGGgAAaTGGGggAaCcGGCGAGAGGGTTCCTCGCTAAGTGGGGGAAATaGGGGAAA
GGTTGACCAGTGGTtCCCcGCTCTCGTAACATGCCTCAGATAGCGCCATCCGCTGTACCT
GGtcaggtcGctggcaacttcggccgagcaggtgaacccgaaaggtgagggtcagtgtga
cacaccaaccgaacaccgacgaggcaagcgtaggagccggcgtggccgcgcccggcggcg
ctgaggactcctcg
But shows the output by skipping the first two lines.
What is the reason for this?
You don't need the while loop, or the readLine method. Just call jtextArea1.read(reader, "jTextArea1")
Edit: update following your comment. If you want to skip all lines starting with >, you will need to read the file manually and then append each line to your textArea.
So something like:
String line;
while ((line = reader.readLine()) != null)
{
if (!line.startsWith(">"))
{
jTextArea.append(line + "\n");
}
}
Use:
FileReader reader = new FileReader("filename.txt");
txtarea.read(reader, "filename.txt"); //Object of JTextArea
You need only the above two lines to read from a file and put it into JTextArea...
The problem must have been solved by the time, yet there's still no answer to the question why the first two lines are skipped.
You create reader and then read the first two lines from the file, remaining lines are loaded into jTextArea1.
Your code:
/* 1 */ while((textLine=reader.readLine())!=null){
/* 2 */ textLine = reader.readLine();
/* 3 */ jTextArea1.read(reader,"jTextArea1");
}
Line 1 reads the first line from the file. Then in the body of while you read the second line from the file at line 2. Line 3 reads the rest of the file into jTextArea1.
On the next iteration of the while loop, reader.readLine() returns null since the file is completely read.
To load text in a JTextComponent use its read method as suggested by Phill and Bhushankumar.
The second parameter to read is not used by JTextArea, so it's safe to pass null. This second parameter is usually used to store to URL of the loaded file to resolve relative references, for example links in an HTMLDocument.
textLine = reader.readLine(); is called twice...
Fixed:
try {
String textLine;
FileReader fr = new FileReader("ad.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null){
// textLine = reader.readLine(); // Remove this line
jTextArea1.read(reader, "jTextArea1");
}
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
Correctly is:
try {
FileReader fr = new FileReader("tablica.txt");
BufferedReader reader = new BufferedReader(fr);
do {
l.read(reader, null);
}
while ((textLine=reader.readLine()) != null)
;
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}