I\'m currently working on a lab in my cpe class and we have to create a simple program that scans in strings from a .txt file and prints them to a different .txt file. So fa
We can do this by reading the file using FileInputStream object and write into another file using FileOutputStream object.
Here is the sample code
package java_io_examples;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Vector;
public class Filetest {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("D:\\testout.txt");
int i = 0;
String s = "";
while((i=fin.read())!=-1) {
s = s + String.valueOf((char)i);
}
FileOutputStream fout = new
FileOutputStream("D:\\newtestout1.txt");
byte[] b = s.getBytes();
fout.write(b);
fout.close();
System.out.println("Done reading and writing!!");
} catch(Exception e){
System.out.println(e);
}
}
}
You need to figure out where it looks for the "input"
file. When you just specify "input"
it looks for the file in the current working directory. When working with an IDE, this directory may not be what you think it is.
Try the following:
System.out.println(new File("input").getAbsolutePath());
to see where it looks for the file.
May be you are just forget the flush()
try {
File input = new File("input");
File output = new File("output");
Scanner sc = new Scanner(input);
PrintWriter printer = new PrintWriter(output);
while (sc.hasNextLine()) {
String s = sc.nextLine();
printer.write(s);
}
**printer.flush();**
}
catch (FileNotFoundException e) {
System.err.println("File not found. Please scan in new file.");
}
public void readwrite() throws IOException
{
// Reading data from file
File f1=new File("D:/read.txt");
FileReader fr=new FileReader(f1);
BufferedReader br=new BufferedReader(fr);
String s = br.readLine();
// Writing data
File f2=new File("D:/write.txt");
FileWriter fw=new FileWriter(f2);
BufferedWriter bw=new BufferedWriter(fw);
while(s!=null)
{
bw.write(s);
bw.newLine();
System.out.println(s);
s=br.readLine();
}
bw.flush();
bw.close();
}
When accessing files with Java I/O, you must include the file's filetype extension (if one exists).
File input = new File("input.txt");
File output = new File("output.txt");