неділя, 18 січня 2015 р.

How to read/write data in text file

1. reading text file




public class TestReadTextFile {

public static void main(String[] args) throws IOException{

ArrayList<String> readFile = ReaderWriter.readFileToArrayList("text.txt");

ReaderWriter.printParsedFile(readFile);
}
}

The result will be:
mary
natali
ivan
in the Console

2.writing data in text file

public class TestWriteTextFile {

public static void main(String[] args) throws IOException{

ArrayList<String> writeArrayToList = new ArrayList<String>();

writeArrayToList.add("1");
writeArrayToList.add("2");
writeArrayToList.add("3");
writeArrayToList.add("4");
writeArrayToList.add("5");

ReaderWriter.writeArrayToFile("testfileToWrite", writeArrayToList);
}
}

The result will be
1
2
3
4
5
in the text file "testfileToWrite"

3. public class ReaderWriter {

public static ArrayList<String> readFileToArrayList(String fileToRead) throws FileNotFoundException{

File file = new File(fileToRead);
   ArrayList<String> names = new ArrayList<String>();
   Scanner in = new Scanner(file);
   while (in.hasNextLine()){
       names.add(in.nextLine());
   }
   in.close();
 
   return names;
}

public static Map<Integer,String> readFileToMap(String fileToRead) throws FileNotFoundException{

FileInputStream file = new FileInputStream(fileToRead);

   Map<Integer, String> names = new HashMap<Integer,String>();
   Scanner in = new Scanner(file);
   int key = 0;
   while (in.hasNextLine()){
    key=key+1;
       names.put(key, in.nextLine());
     
   }
   System.out.println(names);
   in.close();
 
   return names;
}

public static void writeArrayToFile(String fileToWrite, ArrayList<String> arrayListToWrite) throws IOException{
 
FileWriter fw = new FileWriter(fileToWrite);
    BufferedWriter bw = new BufferedWriter(fw);
    for (String s : arrayListToWrite){
    bw.write(s + "\n");//write text to the file using write method
    }
    bw.flush();//write any buffered text to the file
    bw.close();//close file using close() method
}

public static void printParsedFile(ArrayList<String> arrayListFromFile){
for (String s : arrayListFromFile){
System.out.println(s);
}
}

4. Put the "text.txt" and "testfileToWrite" directly as a child of the project root folder and a peer of src



Немає коментарів:

Дописати коментар