File operations in Java are simple as you will see. In the next example we will get file from a specified place then we will read the file line by line and then we will write to file. Lets start
1 ) Firstly we should get file.
File file = new File("C:/can/donusturulecek.txt");
2 ) Then we mostly use Buffered Reader to get content of the file
BufferedReader reader= new BufferedReader(new FileReader(file));
3 ) and then we can traverse the file line by line
while (reader.ready()) {
String read = reader.readLine();
System.out.println(read);
}
4 ) After the operation logic finished you should close the connection
reader.close();
!!If the connection is opened, after some operations it may give a error.
5 ) Lets write now to the file
try {
BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filefirst.txt"));
for(int i= 0 ; i< splitfirst.length ; i++){
out.write("Hi, Hello");
}
out.close();
} catch (IOException e) {}
in.close();
6 ) If you want to go to a new line at the end of your input to the file you can use
out.newLine();
Below there is whole example that reads file from a specified place and divides the content to the 3 section in the file and saves them different files such as file has content below;
a b c
d e f
g h i
. . .
then this program will save as
filefirst.txt
a
d
g
filesecond.txt
b
e
h
filethird.txt
c
f
i
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Files {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int counter=0;
File file = new File("C:/can/converting.txt");
BufferedReader reader= new BufferedReader(new FileReader(file));
String first="",second="",third="";
while (reader.ready()) {
counter++;
String s = reader.readLine();
System.out.println(s);
if(s.compareTo(" ") != 0){
String[] split = s.split(" ");
first += split[0] + "/";
second += split[1]+ "/";
third += split[2]+ "/";
}
}
in.close();
try {
String[] splitfirst = first.split("/");
BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filefirst.txt"));
for(int i= 0 ; i< splitfirst.length ; i++){
out.write(splitfirst[i]);
out.newLine();
}
out.close();
} catch (IOException e) {}
in.close();
try {
String[] splitfirst = second.split("/");
BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filesecond.txt"));
for(int i= 0 ; i< splitfirst.length ; i++){
out.write(splitfirst[i]);
out.newLine();
}
out.close();
} catch (IOException e) {}
in.close();
try {
String[] splitfirst = third.split("/");
BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filethird.txt"));
for(int i= 0 ; i< splitfirst.length ; i++){
out.write(splitfirst[i]);
out.newLine();
}
out.close();
} catch (IOException e) {}
in.close();
}
}
No comments:
Post a Comment