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
Related
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
This question already has answers here:
How to Write text file Java
(8 answers)
Closed 5 years ago.
public static void main(String[] args) {
File newTxt = new File("C:/Users/cauan/Desktop/newTxt.txt");
if(newTxt.exists()) System.out.println("The file already exists!");
else {
try{
newTxt.createNewFile();
FileWriter fw=new FileWriter(newTxt);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("This is my Prog");
}
catch(Exception e){e.printStackTrace();}
}
}
This is my code.... But i dunno why am i getting an error :/
You need to close the BufferedWriter and FileWriter in order to save the contents of the file.
bw.close();
fw.close();
Complete program link
This question already has answers here:
How to write an ArrayList of Strings into a text file?
(8 answers)
Closed 6 years ago.
I want to write the ArrayList<Double> array into the file in such a way that when I double click on the file then the file opens and the user can read the data.
I have tried the DataOutputStream & RandomAccessFile; both works fine but when I double click on the file it shows data which is not in readable form.
I tried this:
ArrayList<Double> larr=new ArrayList<Double>();
larr.add(5.66);
larr.add(7.89);
try{
FileOutputStream fos = new FileOutputStream("out.txt");
DataOutputStream dos = new DataOutputStream(fos);
for(Double d:larr)
dos.writeDouble(d);
dos.close();
} catch(Exception ex) {
ex.printStackTrace();
}
But now the case is that when I open the file out.txt by double clicking on it. It comes in non-readable form.
I would use a PrintWriter to get human readable values to out.txt (and I would specify the parent folder, personally; I like the user's home directory). Also, I would prefer a try-with-resources close and a method. Something like,
public static void writeList(List<Double> al) {
File f = new File(System.getProperty("user.home"), "out.txt");
try (PrintWriter pw = new PrintWriter(f)) {
for (Double d : al) {
pw.println(d);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Also, you could declare and initialize larr1 in one line like
List<Double> larr = new ArrayList<>(Arrays.asList(5.66, 7.89));
1And please program to the List interface.
It's because the I/O streams you said you tried to use (DataOutputStream and RandomAccessFile) are treating the numbers as binary data, rather than text. You should use a PrintStream.
Example:
PrintStream ps = new PrintStream(new File(filePath));
ps.println(5.25);
ps.close(); // Be sure to close the stream when you're done with saving the numbers
Noticed something familiar with ps.println(5.25)? System.out.println(5.25) does exactly the same thing to the console.
This question already has answers here:
Write to text file without overwriting in Java
(9 answers)
Closed 8 years ago.
Hi there I'm trying to write strings to a textfile but there is a little problem. I completed my code with the help of the other questions at this site but when i try to add strings to a text file it erases everything in that text file and writes the input. But I want it to go to the nextline and write it. I couldn't solve it. I would appreciate any help. Thank you..
public static void addCar() throws IOException{
String string = transferBrand;
String string2 = ":"+transferModel;
System.out.println(string+string2);
File file = new File("HatchBack.txt");
try {
StringReader stringReader = new StringReader(string+string2);
BufferedReader bufferedReader = new BufferedReader(stringReader);
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for(String line = bufferedReader.readLine(); line != null; line =bufferedReader.readLine()) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
(untested) Did you try this as mentioned in JavaDoc?
FileWriter fileWriter = new FileWriter(file, true);
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
I am trying to generate random numbers as ids, and save them in a file to easily access them. I am currently using BufferedWriter in order to write these to the file, but the problem is that I am not too sure about how to go about finding where I should start writing into the file. I am currently trying to use BufferedReader to figure out where the next line is to write, but I am not sure how I am supposed to save this offset or anything, or how a new line is represented.
void createIds(){
File writeId = new File("peopleIDs.txt");
try {
FileReader fr = new FileReader(writeId);
BufferedReader in = new BufferedReader(fr);
FileWriter fw = new FileWriter(writeId);
BufferedWriter out = new BufferedWriter(fw);
String line;
while((line = in.readLine()) != null){
//How do I save where the last line of null is?
continue;
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
If you simply want to add IDs to the end of the file, use the following FileWriter constructor:
FileWriter fw = new FileWriter(writeId, true);
This opens the FileWriter in append mode, allowing you to write output to a pre-existing file.
If you would like to write the IDs to a particular location within an existing file rather than just to the end, I am not sure if this is possible without first parsing the file's contents.
For more information, see the JavaDoc for FileWriter.
We need more information about the file itself: what are you searching for with BufferedReader?
If the file is empty/newly created then you don't need BufferedReader at all. Just create the PrintWriter and save your numbers.
I'm just guessing here, but I think the real problem is that you're not sure how to generate random numbers (since this doesn't appear in your example code).
Here's some example code that'll write random numbers into a text file:
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Example
{
public static void main(String[] args)
{
Random r;
PrintWriter writer;
r = new Random();
try
{
writer = new PrintWriter(new BufferedWriter(new FileWriter("Examplefile.txt")));
for (int i = 0; i < 10; i++)
writer.println(Integer.toString(r.nextInt(10)));
writer.close();
}
catch (IOException e)
{
}
}
}
You can do
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File("abc.txt"),true)));
writer.append("test");
} catch (IOException e) {
e.printStackTrace();
}