so i'm trying to read from a file a number of lines, and after that put them in a String[]. but it doesn't seem to work. what have i done wrong?
String[] liniiFisier=new String[20];
int i=0;
try{
FileInputStream fstream = new FileInputStream("textfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
liniiFisier[i]=strLine;
i++;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
for(int j=0;j<i;j++)
System.out.println(liniiFisier[i]);
Change that last line to
System.out.println(liniiFisier[j]); // important: use j, not i
You should tell us what's happening and what problem occurred.
But I yet see some errors:
Imagine your file has more than 20 lines, so you'll try to access liniiFisier[20], but this field is not present! Results in ArrayIndexOutOfBounds
In your for loop you are iterating j but always using i...
Creating the BufferedReader can be done in less code:
FileReader fr = new FileReader ("textfile.txt");
BufferedReader br = new BufferedReader (fr);
Since I don't know about your particular problem this might not solve it, so please provide more information ;-)
Related
So if I have a txt file like this:
scissors 3
papers 5
staplers 2
How do I only read the integers with a bufferedreader and not using scan.
try {
BufferedReader reader = new BufferedReader(new FileReader("Supplies.txt"));
String line = "";
while((line=reader.readLine())!=null){
System.out.println(line);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
How do I only read the integers with a bufferedreader and not using scan.
Assuming I understand your question, you could use your current code, and add a regular expression to remove everything that isn't a digit before parsing the int value. Like,
while ((line = reader.readLine()) != null) {
int i = Integer.parseInt(line.replaceAll("\\D+", ""));
System.out.println(i);
}
You should close() your reader when you finish with it, otherwise you leak a file handle. I believe the best solution is a try-with-resources. Like,
try (BufferedReader reader = new BufferedReader(new FileReader("Supplies.txt"))) {
// BufferedReader reader = new BufferedReader(new FileReader("Supplies.txt"));
What i'm trying to do, is to replace a symbol in a file text which contains over 4000 lines but using the below code, after the program ends, it only remain 500 lines. Why is this file truncated? How to solve this?
This is my code:
ArrayList<String> arrayList = new ArrayList<>();
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {System.err.println(e);}
}
} catch (Exception e) {e.printStackTrace();}
Thanks in advance!
new BufferedWriter(new FileWriter(file)) clear file.
You should open it only once. Also you reading and writing to the same file. You should use different files.
Like this
try (FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
bw.write(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
You are writing to the same file while you are reading it. This won't work. Once you start writing, the file becomes empty (plus whatever you've written), so subsequent reads will report end-of-file. Your ~500 lines will be buffered input from the first read.
One solution is to do all the reading first, before opening the file again for writing:
Array<String> arrayList = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
while ((String line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {
System.err.println(e);
}
Here, first the program slurps the file into a List<String>, fixing the lines as it goes. Then it writes all the lines back out to the file.
There are circumstances in which this model is appropriate. For example, you might be building a non-linear data structure from the file content. Or you might need to see the last line before you can modify earlier lines (and be unable to re-open the data source from the start).
However I'd suggest a method that's more thrifty with memory. You don't need to keep all those lines in memory. You can read one line, fix it up, then forget about it. But to do this, you'll need to write to a second file.
String filein = "inputfile";
String fileout = filein + ".tmp";
try(
BufferedReader reader = new BufferedReader(new FileReader(filein));
Writer writer = new BufferedWriter(FileWriter(fileout))
) {
while ((String line = bufferedReader.readLine()) != null) {
writer.write(line.replace("þ", "t");
}
}
Files.move(Paths.get(fileout)),
Paths.get(filein),
CopyOption.REPLACE_EXISTING);
I have left out the necessary exception catching -- add back in as required.
I am writing a method for my java class. it looks like this so far:
String file_name;
String line;
void addLine(file_name, line){
int line_number;
try {
FileWriter writer = new FileWriter(file_name, true);
PrintWriter out = new PrintWriter(writer);
out.println(line_number + line);
}
catch (IOException e){
System.out.println(e);
}
}
How should I define line_number so it would check how many lines were there in file before I printed out next into it?
int totalLines = 0;
BufferedReader br br = new BufferedReader(new FileReader("C:\\filename.txt"));
String CurrentLine = "";
while ((CurrentLine = br.readLine()) != null) {
++totalLines
}
i think you have to actually read the file by using a bufferedreader. and then keep on incrementing the totalLines till it reach the end of the file
You can count them with a function posted here: Number of lines in a file in Java
They tested it with a 150 MB log file and it seems to be fast.
I am currently reading in a file into java where the file contains list of ("char symbol" "tab" "6 comma seperated booleans" "new line")
I am reading it in fine and splitting it up ok - however i have a problem whereby the pound sign and speech marks are being read in as a black diamond with a question mark in it. This is screwing everything up as i need to be able to identify which codes go with which char symbol.
I am reading in using:
public void read()
{
int i = 0;
try{
// Open the file
InputStream is = am.open("combinations.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(is);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null && i < 53) {
String[] sep1 = strLine.split("\t");
String[] sep2 = sep1[1].split(",");
entries[i] = new Entry(sep1[0].charAt(0), new CellPattern(Boolean.valueOf(sep2[0]),
Boolean.valueOf(sep2[1]),Boolean.valueOf(sep2[2]),Boolean.valueOf(sep2[3]),
Boolean.valueOf(sep2[4]),Boolean.valueOf(sep2[5])));
i++;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
It is an encoding problem, try changing your BufferedReader line to:
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
I'm not sure which encoding you'll need, so you may want to try a few different ones.
Edit:
Try "ISO-8859-1"
I'm trying to read a simple text file that contains the following:
LOAD
Bill's Beans
1200
20
15
30
QUIT
I need to store and print the contents line by line. I am doing so using the following code:
String inputFile = "(file path here)";
try {
Scanner input = new Scanner(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String currentLine = "";
while (!currentLine.equals("QUIT}")){
currentLine = input.nextLine();
System.out.println(currentLine);
}
input.close();
However, the output is very "messy". I am trying to avoid storing all new line characters and anything else that doesn't appear in the text file. Output is:
{\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf540
{\fonttbl\f0\fmodern\fcharset0 Courier;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\deftab720
\pard\pardeftab720\ql\qnatural
\f0\fs26 \cf0 LOAD\
Bill's Beans\
1200\
20\
15\
30\
QUIT}
Any help would be greatly appreciated, thank you!
This looks like you're reading a RTF file, isn't that so, by any chance?
Otherwise, I found reading text files is most natural for me using this construct:
BufferedReader reader = new BufferedReader(
new FileReader(new File("yourfile.txt")
);
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
// do whatever with the text line
}
Because this is an RTF file, look into this for example: RTFEditorKit
If you insist on writing your own RTF reader, the correct approach would be for you to extend FilterInputStream and handle the RTF metadata in its implementation.
Just add following code into your class, then call it with path parameter. it returns all lines as List object
public List<String> readStudentsNoFromText(String path) throws IOException {
List<String> result = new ArrayList<String>();
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File(path));
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
result.add(strLine.trim());
}
//Close the input stream
in.close();
return result;
}