Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this project for the university where they're asking me to create a simple bank system in Java. So far I've been able to do well except when it comes to store data for using it next time..
Lately I've found the storing code where all of my data are stored on a text file as :
int str str int
5487,Samer,Lebanon,1000000
8792,Ahmad,Lebanon,2500000
and so on using the io libraries such as :
public static void saveToFile(int[] accounts,String[] names,String[] addresses,int[] balances,int maxTmp) {
bubbleSorting(accounts,names,addresses,balances,maxTmp);
try {
//What ever the file path is.
File statText = new File("C:/Users/Wicked Angel/Desktop/customers.txt");
FileOutputStream is = new FileOutputStream(statText);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
for(int i=0;i<maxTmp;i++)
w.write(accounts[i] + "," + names[i] + "," + addresses[i] + "," + balances[i] + System.getProperty("line.separator"));
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file customers.txt");
}
}
The difficulty is when I'm trying to import that text file and set each value to its specific array..
Any help ?
First, you have to read the text file line by line
// your file
File statText = new File("C:/Users/Wicked Angel/Desktop/customers.txt");
// read file using FileReader class
FileReader fr = new FileReader(statText);
BufferedReader br = new BufferedReader(fr);
// the first line is the header line and might be ignored
String line = br.readLine();
// loop through each line by reading it from the buffer
while ((line = br.readLine()) != null) {
// process each line
}
br.close();
This will loop through each lines in your file. The line will be a string. Here below is an example of the first string in the while loop.
line: "5487,Samer,Lebanon,1000000"
What you have to do is to separate each parts and bring it to an array. This can be done with the Split() method from String-object. (click on the method name to read the documentation).
String[] myParts = line.Split(",");
The result will be then
myParts: ["5487"] ["Samer"] ["Lebanon"] ["1000000"]
That's an array. Just go through the above array and store each variable in the appropriate array. The first element in ArrayList<int> accounts, the second element in ArrayList<String> names ... Here below is an example for the first element
// outside loop
ArrayList<int> accounts = new ArrayList<int>();
// inside loop
accounts.Add(Integer.parseInt(myParts(0)));
// since it should be an integer, I parse it to int before adding it
The reason behind the use of ArrayList is because you don't know how many lines you have in your text. Ofc you can check it, but performance wise, it's advisable to use a dynamic array, which is ArrayList. (Or other list objects if you want). If you want to read more about ArrayList, please refer to this documentation to create, add element, get element, ...
Oh, also don't forget to cast the first and third element to int, or you will get errors when trying to add these info in an int ArrayList. If you want, you can also validate each element to ensure that you don't have faulty data (like the result of splitting a line is an array of three elements, which is incorrect).
This should help you to solve your import problems. Good luck
use your ',' as the delimiter. read each line and seperate them using delimiter like, say if i wanted to extract String text="holy,molly" i would do
String holy=text.substring(0,text.indexOf(','));
and
String molly=text.substring(text.indexOf(','))
Related
I'm trying to split each line from a text file into cells in an Array. Can I do it with split function and not count the lines in order to create an array?
I am using Scanner for reading files from Scanner. The file contains in each line the following format: number_number
I want to save number_number as a string into a cell in Array.
However, I don't know how many lines in my text file could be, in order to set an array size. I dont want to useLinkedList`, please use the assumption that will not have many lines.
Is it possible to read from file and save each line into cell in array?
There is no problem to change the method from Scanner to another one.
The problem in my code currently that it saves only the first line in my file.
public String[] readFromFileToStringArray(String s) {
Scanner scanner = null;
try {
scanner = new Scanner(new File(s));
} catch (IOException e) {
e.printStackTrace();
}
String[] fileText = null;
if (scanner != null)
while (scanner.hasNext())
fileText = scanner.nextLine().split("\n");
return fileText;
}
When using scanner.nextLine() you read the text until the \n character, so the split you did is pointless since the line string won't have this character.
You can read all the file and then split it:
public String[] readFromFileToStringArray(String s) {
String text = new String(Files.readAllBytes(Paths.get(s)),
StandardCharsets.UTF_8);
return text.split("\n");
}
But really as the other answered said, it would probably be better to simply use List
Should you change the way to add string to the array?
fileText.add(scanner.nextLine());
OR:
List<String> list = new ArrayList<String>(Arrays.asList(fileText));
list.addAll(Arrays.asList(scanner.nextLine().splite("\n")));
String[] fileText = list.toArray();
List<String> lines = Files.readAllLines(pathToFile);
java Files is the easiest way for this.
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);
}
}
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my program, I am asking users for input for a subject name and a subject code which i pass through to a subjects.txt file eg:
Inside the TestSubject class -
//ask the user to input a subject name
System.out.println("Please enter a Subject Name");
//assign each input to a side
String subjectName = input.nextLine();
//ask the user to input a subject code
System.out.println("Please enter a Subject Code");
String subjectCode = input.nextLine();
//add records to the file
subject.addRecords(subjectName, subjectCode);
Inside the subject class -
//add the records of valid subject name and subject code
public void addRecords(String name, String code) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("subjects.txt", true)))) {
out.printf(name);
out.printf("\n");
out.printf(code);
out.printf("\n");
out.close();
}catch (IOException e) {
}
}
I then want to read this file and pass the data through to an arraylist. The file might look something like:
Testing 1
ABC123
Testing 2
DEF456
Testing3
GHI789
I want to pass it through to an arraylist so then I can then process other methods against this array such as sorting, see if any are the same etc.
//read data from subjects file and place in an array
public void readData(){
Scanner input = new Scanner("subjects.txt");
while (input.hasNext()) {
String subjectName = input.nextLine();
String subjectCode = input.nextLine();
}
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//add the input to the arrays
subjectNames.add(subjectName);
subjectNames.add(subjectCode);
//display the contents of the array
System.out.println(subjectNames.toString());
System.out.println(subjectCodes.toString());
}
Even if there is a good tutorial around that I might be able to be pointed in the right direction...
Thanks for editing your post. Much easier to help when I can see what's causing problems.
You're checking hasNext() once every two lines. Should be checked every line because you shouldn't trust the text file to be what you expect and should display an informative error message when it isn't.
You're also declaring the strings inside the scope of the loop so nothing outside the loop even knows what they are. Shoving subjectCode into into the subjectNames collection is probably not what you want. As it is, each nextline() is stepping on the last string value. That means you're forgetting all the work done in previous iterations of the loop.
The collections.add() calls, not the strings, should be in the loop. Make sure to declare the collections before the loop and put their add calls in the loop. See if you get useful results.
Give "Reading a plain text file in Java" a read.
Regarding your tutorial query, I often find some good basic examples on this site including one for reading from a file as referenced in the link. Using the main principles of that example here is one way you could try and read the lines from your file:
public static void main(String[] args){
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//Path leading to the text file
Path data = Paths.get(System.getProperty("user.home"), "Desktop", "file.txt");
int count = 0;//Will indicate which list to add the current line to
//Create a buffered reader to read in the lines of the file
try(BufferedReader reader = new BufferedReader(new FileReader(data.toFile()))){
String line = "";
while((line = reader.readLine()) != null){//This statement reads each line until null indicating end of file
count++;//Increment number changing from odd to even or vice versa
if(count % 2 == 0){//If number is even then add to subject codes
subjectCodes.add(line);
} else {//Otherwise add to subject names
subjectNames.add(line);
}
}
} catch (IOException io){
System.out.println("IO Error: " + io.getMessage());
}
System.out.println("Codes: ");
display(subjectCodes);
System.out.println("\nNames: ");
display(subjectNames);
}
private static void display(Collection<String> c){
for(String s :c){
System.out.println(s);
}
Hope it helps!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have this method which receive as parameters pdfText(which is a String containing text from a pdf file after parsing) and fileName which is the file where i want to write that text
But now I need to find the word "Keywords" in this text and extract only the words after it,which are in the same line(until the newline character).
For example I have one text which contains somewhere the following line
Title:Something.
"Keywords : Computers, Robots, Course"
Tags:tag1,tag2,tag3.
And the result should be the following list ["Computers","Robots", "Course"].
Solved Question
So I've searched how to solve my question..here is a solution,not very smart but it works:
//index of first appearence of the word
int index = pdfText.indexOf("Keywords");
//string from that to the end
String subStr = pdfText.substring(index);
//index of first appearence of the new line in the new string
int index1 = subStr.indexOf("\n");
//the string we need
String theString = subStr.substring(9,index1);
System.out.println(theString);
//write in the file..use true as parameter for appending text,not overwrite it
FileWriter pw = new FileWriter(fileName,true);
pw.write(theString);
pw.close();
Honestly, this question is too situation specific. Regardless :)
Writing to file
String pdfText = "pdfText";
String fileLocation = "fileLocation";
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileLocation), "utf-8"));
writer.write(pdfText); // String you want to write (i.e. pdfText)
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {writer.close();} catch (Exception ex) { ex.printStackTrace(); }
}
It's always a good idea to specify the encoding type. ("utf-8"). It might not matter for your assignment though. You might also need to append to the file, and not re-write it completely, in which case, you should use a different constructor for the FileOutputStream, new FileOutputStream(getFileLocation(), true) . As for the many try/catch blocks, don't follow my example. It's how I manage to close my resource, as eclipse recommends haha.
Parsing the String
If you have a line such as "Keywords : Computers, Robots, Course",
String str = "Keywords : Computers, Robots, Course";
String[] array = str.substring(indexOf(':') + 1).split(",");
//this array = ["Computers", "Robots", "Course"]
Now you have an array which you can loop through and write/print out however you'd like.
You could use regex to extract the words after the word "Keyword:" like this :
String regex = ".*Keywords\\s*:(.*)\\n.*";
String extractedLine = yourText.replaceAll( regex, "$1" );
System.out.println( extractedLine );
This question already has answers here:
Inserting text into an existing file via Java
(8 answers)
Closed 9 years ago.
I want to insert a line into a specific location of a .txt file. Now the only way I know is to read out the whole file out as an array, put the given line in the correct place and then write the whole thing back. Is there an easier way to achieve this using Java? My intention is to reduce the file access as much as possible.
Is there an easier way to achieve this using Java?
With Java 7, unless your insertion point is towards the end of a huge file, I would simply do:
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);
Try to read and write at the same time by using BufferedReader.
The Idea is to read line and immediately write it to other file.
BufferedReader rd = null;
BufferedWriter wt = null;
try {
rd = new BufferedReader(
new InputStreamReader(
new FileInputStream("/yourfile.txt"), "UTF-8")
);
wt = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(
"/newfile" + ".txt"), "UTF-8")
);
int count = 0;
for (String line; (line = reader.readLine()) != null;) {
count++
if (count == 6) {
// add your line
// wt.write(newline);
}
wt.write(line);
wt.newLine();
}
} finally {
close(wt);
close(rd);
}
RandomAccessFile do not solve this problem. It was discussed in this post. You should rewrite file anyway.
You can only read and write it with some buffer, alter it and immidiate write to new to save your program memory.