This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 4 years ago.
i would like to build a text data-cleaner in Java, which
cleans the text from Smileys and other special charakter. I wrote a text reader,
but he stops after 3/4 of Line 97 and i just don't know why he does it? Normally he should read the complete text file (ca. 110.000 Lines) and then stop. It would be really nice if could show me where my mistake is.
public class FileReader {
public static void main(String[] args) {
String[] data = null;
int i = 0;
try {
Scanner input = new Scanner("C://Users//Alex//workspace//Cleaner//src//Basis.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
data[i] = line;
i++;
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(data[97]);
}
}
Your mistake is here:
String[] data = null;
I would expect this code to throw null pointer exception...
You can use ArrayList instead of plain array if you want to have dynamic re-sizing
Related
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.
This question already has answers here:
How to Write text file Java
(8 answers)
Closed 6 years ago.
I have Come across so many programmes of how to read a text file using Scanner in Java. Following is some dummy code of Reading a text file in Java using Scanner:
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
But, please anyone help me in "Writing" some text (i.e. String or Integer type text) inside a .txt file using Scanner in java. I don't know how to write that code.
Scanner can't be used for writing purposes, only reading. I like to use a BufferedWriter to write to text files.
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("Write the string to text file");
out.newLine();
Scanner is for reading purposes. You can use Writer class to write data to a file.
For Example:
Writer wr = new FileWriter("file name.txt");
wr.write(String.valueOf(2)) // write int
wr.write("Name"); // write string
wr.flush();
wr.close();
Hope this helps
This question already has answers here:
Reading a plain text file in Java
(31 answers)
Closed 8 years ago.
I need to read a file with this format:
[user1, user2, user3]
Then I need to store it in an ArrayList.
I have no idea about reading files and so..
Thanks for the help and sorry for my bad english :)
Okay guys, I wrote some code and I got this:
public static String getGroups(int index) {
try {
for (int i = 0; i < countLines(); i++) {
String[] content = new String[countLines()];
File file = new File(getIndexValues(i, 1));
try {
FileReader reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content[i] = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return content[index];
}
} catch (IOException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
It returns all the content in the file I want. I have a list of files so if I type getGroups(0) it will take the first line of the index file and will look for it's path to load it.
Now, how can I put the output in an ArrayList?
I need to load it in a JList.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I just started to learn Java. As the title says... I would like to know how should I assign some values from a txt files to an array in Java to work with them (for example to sort them).
For example in C++:
#include<fstream>
using namespace std;
int v[10];
int main()
{
ifstream fin("num.txt");
int i;
for(i=0;i<10;i++)
fin>>v[i];
}
Right guys. Thank you for all the information. I see that is a little bit more complicated than C++, but I'll learn this. Furthermore, when I was intern at a small company I saw that the employees there made a code which scanns an XML files. I guess it's much more complicated, but that's fine. :)
If each line of the file is an integer then:
List<Integer> results = new ArrayList<Integer>();
try
{
File myFile = new File("./num.txt");
Scanner scanner = new Scanner(myFile);
while (scanner.hasNextInt())
{
results.add(scanner.nextInt());
}
}
catch (FileNotFoundException e)
{
// Error handling
}
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=read%20text%20file%20java
I believe this might help you find a solution.
Alright, getting that trolling out of the way.
PSEUDO CODE:
while not end of file
get next line
put next line in a Array List
Remember each line is a String you can parse strings with .split() to get all the words from the file or use some REGEX magic.
EDIT:
Ok I saw the other anwser and scanner.nextInt() makes me cringe. I had to show an actual code implementation. Using a REGEX to denot the pattern, is a farm more superior method. You can be reading garbage data for all you know! Even if REGEX is beyond you at the moment they are so freaking useful it's important to learn the correct method to do something.
List<Integer> list = new ArrayList<Integer>();
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
if(line.matches("[\\s\\d]+"){
String[] temp = line.split(" ");
for(int i = 0; i < temp.length; i++){
list.add(Integer.parseInt(temp[i]));
}
}
}
The following program will read each character in the file to an ArrayList. In this example white spaces are loaded into the ArrayList, so if this is not intended you have to work some aditional logic :)
If the intention is to fill the array with words instead of characters, make a StringBuilder and inside the loop replace the logic with sb.append(new String(buffer));
Then, as progenhard suggested, use the split() method on the returning String from StringBuilder;
public class ReadFile {
public static void main(String[] args){
FileInputStream is = null;
try{
File file = new File("src/example/text");
is = new FileInputStream(file);
byte[] buffer = new byte[10];
List<Character> charArray = new ArrayList<Character>();
while(is.read(buffer) >=0){
for(int i=0;i < buffer.length;i++)
charArray.add((char)buffer[i]);
//Used remove the assigned values on buffer for the next iteration
Arrays.fill(buffer, (byte) 0);
}
for(char character : charArray){
System.out.println(character);
}
}catch(IOException e){
System.out.println("Something wrong with the file: " + e);
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
System.out.println("Something wrong when closing the stream: " + e);
}
}
}
}
}
This question already has answers here:
Android read text raw resource file
(14 answers)
Closed 3 years ago.
I'm currently trying to read a file from (res/raw) by using an InputStream that I dimension like such:
InputStream mStream = this.getResources().openRawResource(R.raw.my_text_file_utf_8);
I then put that into this method to return the values:
public List<String> getWords(InputStream aFile) {
List<String> contents = new ArrayList<String>();
try {
BufferedReader input = new BufferedReader(new InputStreamReader(aFile));
try {
String line = new String();//not declared within while loop
while ((line = input.readLine()) != null ){
contents.add(line);
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents;
}
My problem: It reads all the values as it should, but say if the file is 104 lines long, it will actually return a value of something like 134 total lines with the remaining 30 lines being full of null??
Have checked: Already using UTF-8 format, and double checked that there are literally no blank lines within the document itself...
I thought the way the while loop was written that it couldn't record a line=null value to contents List? Am I missing something here?
Thanks for any constructive information! I'm pretty sure I'm overlooking some simple factoid here though...
Why dont you create HTML for your information and then parse it.