I am trying to create a uid generator with java using file writer and reader I want it to generate id with serial 1 then 2 then 3 and so. on. but it isn't working correctly I want to store it in file so that it starts from last ended number when program starts again. This is my code
import java.io.*;
import java.util.*;
import java.text.*;
class java{
static void main()throws IOException{try{
Scanner in=new Scanner(System.in);
String s=null;
File f =new File("C:\\DMCH\\U.IDN");
if(!f.exists()){
f.mkdirs();}
else
System.out.print("");
File file =new File("C:\\DMCH\\U.IDN\\uid.txt");
if(!file.exists()){
file.createNewFile();}
else
System.out.print("");
DateFormat uid=new SimpleDateFormat("dMyy",Locale.US);
s=uid.format(new Date())+"00";
Writer fo=new FileWriter("C:\\DMCH\\U.IDN\\uid.txt");
fo.write(s);
fo.close();
System.out.println(s);
FileInputStream fi =new FileInputStream("C:\\DMCH\\U.IDN\\uid.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(fi));
String st=null,tmp;
while((tmp=br.readLine())!=null){
st=tmp;
}
fi.close();
long i=Long.valueOf(st)+1;
System.out.println("Enter getuid to get uid");
String str=in.next();
if(str.equals("getuid"))
{
System.out.println(i);
}
Writer foo=new FileWriter("C:\\DMCH\\U.IDN\\uid.txt");
foo.write(Long.toString(i));
foo.close();
}catch(NumberFormatException n){}
}
}
I want it to generate uid as:
17051701
then
17051702
and so. on.
and I want it to start from last ended point after restarting the program
for example in the above case program must give next uid as:
17051703.
I think you want this. Another time when you ask the question you should put your code. then others can get better understand what you want.
public static void main( String[] args ) {
try {
int fileReader = fileReader();
System.out.println(fileReader + 1);
fileWrite(fileReader + 1);
} catch ( FileNotFoundException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
}
}
private static int fileReader() throws FileNotFoundException, IOException {
File f = new File("E:\\yourlocation\\MyFile.txt");
String value = "0";
if ( f.exists() ) {
FileReader reader = new FileReader(f);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ( (line = bufferedReader.readLine()) != null ) {
value = line;
}
reader.close();
}
return Integer.parseInt(value);
}
private static void fileWrite( int id ) throws IOException {
FileWriter writer = new FileWriter("E:\\yourlocation\\MyFile.txt", true);
writer.write(id + "");
writer.write("\r\n"); // write new line
writer.close();
}
Related
I'm having an issue with changing a line in a file, the purpose of this code is to change the first number of the file to itself + 1. For some reason the code doesn't seem to be functioning at all, any help would be appreciated!
public static void changenumber(String fileName)
{
ArrayList<String> list = new ArrayList<String>();
File temp = new File(fileName);
Scanner sc;
try {
sc = new Scanner(temp);
while (sc.hasNextLine())
{
list.add(sc.nextLine());
}
sc.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
String first = list.get(0);
int i = Integer.parseInt(first);
i = i+1;
first = Integer.toString(i);
list.set(0, first);
writenumber(list,fileName);
}
public static void writenumber(ArrayList<String> list, String fileName)
{
PrintWriter write;
try {
write = new PrintWriter(new FileWriter(fileName, true));
for(int i = 0; i<list.size();i++)
{
write.append(list.get(i));
}
}
catch(IOException err)
{
err.printStackTrace();
}
}
Your problem is that you never closed the FileWriter.
Use try-with-resources to ensure that file streams are closed correctly.
A few other improvements to your code:
Do not ignore exceptions. Continuing execution as-if nothing bad happened will cause lots of problems. Let the exception bounce back to caller, and let caller decide what to do if the file cannot be updated.
Scanner is slow. Since all you're doing to reading lines, use BufferedReader instead.
The lines in memory don't end in newline characters, so you need to use the println() method when writing the lines back out, otherwise the result is a file with all the lines concatenated into a single line.
Variables renamed to be more descriptive.
public static void changenumber(String fileName) throws IOException {
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
for (String line; (line = in.readLine()) != null; ) {
lines.add(line);
}
}
int i = Integer.parseInt(lines.get(0));
i++;
lines.set(0, Integer.toString(i));
writenumber(lines, fileName);
}
public static void writenumber(List<String> lines, String fileName) throws IOException {
try (PrintWriter out = new PrintWriter(new FileWriter(fileName, true))) {
for (String line : lines) {
out.println(line);
}
}
}
Of course, you could simplify the code immensely by using the newer NIO.2 classes added in Java 7, in particular the java.nio.file.Files class.
public static void changenumber(String fileName) throws IOException {
Path filePath = Paths.get(fileName);
List<String> lines = Files.readAllLines(filePath);
lines.set(0, Integer.toString(Integer.parseInt(lines.get(0)) + 1));
Files.write(filePath, lines);
}
I have a text file with the following format:
String1
String1String2
String1String2String3
....
String1Strin2String3.....String(i)...String(n)
I want to remove some parts of this file to have the following format(result file):
String1
String2
String3
...
String(i)
String(n)
I tried with this fonction but my output file is always empty:
public static void FileFormatted(String inputFile,String outputFile)
{
String FileContent = readFile(inputFile,
StandardCharsets.UTF_8);
String[] FileSentences = FileContent.split("[\n]");
for (int i = 0; i < FileSentences.length; i++)
{
StringBuilder builder = new StringBuilder();
for(int j=1;j<FileSentences.length;j++)
{
int index= FileSentences[j].indexOf("FileSentences[i]");
String temp=FileSentences[j].substring(index);
FileSentences[j]=FileSentences[j].replaceAll(temp," ");
builder.append(FileSentences[j]+ "\n");
}
writeIntoFile(builder, outputFile, true);
}
}
public static void writeIntoFile(StringBuilder stringBuilder,
String txtFilePath, boolean append) {
File file = new File(txtFilePath);
// if file doesn't exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter fw;
try {
fw = new FileWriter(file.getAbsoluteFile(), append);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(stringBuilder.toString());
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Can someone please help me.
Okay, first of all reading the whole file in, in one go is bad practice. Imagine you have a 6gb file, that means you need 6gb of RAM to store that file when you read it in. It would be better to read the file line by line.
So the Aim of the logic would be read line by line.
When we read the first line we can get the length of it.
When we read read the second line we know the length of the first line so that means it is our starting point on the second line. This means you can use sub-string method, passing the start position and end position.
And repeat this logic for line 3,4,...n
The benefit of this is that you don't waste memory, you are only storing the size of the line in text.
Update
I have written the code that I suggested earlier. It's pretty basic and there is no validation so you will need to add to it. But it covers the basics
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fileReader);
int startPosition = 0;
String line;
ArrayList<String> items = new ArrayList<String>();
while((line = br.readLine() ) != null)
{
items.add(line.substring(startPosition, line.length()));
System.out.println(line.substring(startPosition, line.length()));
startPosition = line.length();
}
write("test2.txt", items);
}
public static void write (String filename, ArrayList<String> items) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (String item : items) {
outputWriter.write(item);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
be sure the pattern is consistent in the hole file, then Do this:
public static void main(String[] args) {
String wordTofind = "String";
String st = "String1String2String3String4";
String[] arra = st.split(wordTofind);
for (int i = 1; i < arra.length - 1; i++) {
System.out.println(wordTofind + arra[i]);
//write to a file or similar.
}
}
you can use regex too, but this is acceptable...
I have a super beginner's question. I have a computer science test today and one of the practice problems is this:
Write a program that carries out the following tasks:
Open a file with the name hello.txt.
Store the message “Hello, World!” in the file.
Close the file.
Open the same file again.
Read the message into a string variable and print it.
This is the code I have for it so far:
import java.util.*;
import java.io.*;
public class ReadFile
{
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y));
}
in.close();
out.close();
}
}
What's wrong with this code?
1) You need to close the stream
2) You need to refer to the x Arraylist with (y-1) otherwise you will get
a java.lang.IndexOutOfBoundsException . The indexes starts from 0 and not from 1.
http://www.tutorialspoint.com/java/util/arraylist_get.htm
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
out.close();
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
in.close();
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y-1));
}
}
}
I guess what's wrong with the code ist that you cant read anything from the file.
this is because PrintWriter is buffered
fileName - The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
You need to close the file you have just writen to before openning it for reading so that the changes are fluched to the physical storage. Thus moving out.close(); right after out.println("Hello, World");
class FileWritingDemo {
public static void main(String [] args) {
char[] in = new char[13]; // to store input
int size = 0;
try {
File file = new File("MyFile.txt"); // just an object
FileWriter fw = new FileWriter(file); // create an actual file & a FileWriter obj
fw.write("Hello, World!"); // write characters to the file
fw.flush(); // flush before closing
fw.close(); // close file when done
FileReader fr = new FileReader(file); // create a FileReader object
size = fr.read(in); // read the whole file!
for(char c : in) // print the array
System.out.print(c);
fr.close(); // again, always close
} catch(IOException e) { }
}
}
Here is my code. The input consists of names of anime(japanese cartoons) which i have stored it in testfile in anime.txt and I am arranging them in alphabetical order and writing it back into another file name animeout.txt.
The input file does not contain any comma or square bracket but the output file has it.
public class Main {
public static ArrayList<String> read(String filePath) throws IOException {
ArrayList<String> names = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(filePath));
int numRead = 0;
String line;
while ((line = reader.readLine()) != null) {
names.add(line + "\n");
numRead++;
}
System.out.println("\n\n count " +numRead);
reader.close();
System.out.println(names);
return names;
}
public static void write(ArrayList<String> input) throws IOException
{
File file = new File("Animeout.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(input);
writer.flush();
writer.close();
}
public static void main(String args[]) throws IOException
{
ArrayList<String> names2 = new ArrayList<String>();
String path= "anime.txt";
String test;
names2 = read(path);
Collections.sort(names2, null);
// System.out.println(names2);
write(names2);
}
}
Input file has about 200 lines. Below is just a small example
One piece
Naruto/naruto shippuden
Bleach
Fullmetal alchemist brotherhood
Fate/stay night
Fairy tale
Blue exorcist
Soul eater
Death note
Output file contains , and [
count 105
[11 eyes
, A certain magical index
, A certain magical index II
, Aldnoah.Zero
, Angel beats!
, Another
, Asu no yoichi
, Bay blade
, Beelzebub
, Ben-To
String str = "[12,34,45]";
String out = str.replaceAll(",|\\[|\\]","");
output:
123445
Why are you using a ObjectOuputStream? That is intended for when you want to serialise Java objects and restore them later. I don't see why you need it here.
Just use a FileWriter, like so:
public static void write(ArrayList<String> input) throws IOException
{
try
{
File file = new File("Animeout.txt");
FileWriter fw = new FileWriter(file);
for (int i = 0; i < input.size(); i++) {
fw.append(input.get(i) + "\n");
}
}
finally
{
try {
if (fw != null)
fw.close();
}
catch (Exception e) {
// ignore
}
}
}
Your write method is unfortunate. Try something like this instead (and remove the + "\n" when reading the lines):
public static void write(ArrayList<String> lines) throws IOException
{
File file = new File("Animeout.txt");
PrintStream ps = null;
try {
ps = new PrintStream(file);
for (final String line : lines) {
ps.println(line);
}
} finally {
if (ps != null) { ps.close(); }
}
}
The ObjectOutputStream you are using is not appropriate for simply writing lines of text.
Finally, if all you want to do is sorting the lines of a text file, at least on a POSIX system, you can just do it with
$ sort anime.txt > Animeout.txt
from the command line.
This question already has answers here:
Standard concise way to copy a file in Java?
(16 answers)
Closed 8 years ago.
I am trying to read a file and write to another file it is not working I invoke the method from the main
public boolean copy(String inputPlayList, String outputPlayList, int numberOfMunites)
{
String start1 = "#EXTINF:";
String afterNum = ";";
try
{
declaring those variable that I would use to pass the method
File fInput, fOutput;
String s;
String a;
assigning those variable to the method
fInput = new File(inputPlayList);
fOutput = new File(outputPlayList);
// Now I am using bufferedRead and BufferedWriter to read and write in a file
BufferedReader br = new BufferedReader(new FileReader(new File(inputPlayList)));
BufferedWriter out = new BufferedWriter(new BufferedWriter(new FileWriter(outputPlayList)));
// creating a while saying while the line is not finish contunue to read
while((s = br.readLine())!= null)
{
if(s.contains(start1)) {
String numberInString = s.substring(start1.length(), s.indexOf(afterNum));
numberOfMunites+= Integer.getInteger(numberInString);
}
// when it is finsh close the file.
out.write(s);
}
out.close();
System.out.println("donne");
}catch ( IOException e)
{
System.err.println("the is an erro that need to be fixed"+e);
}
return false;
}
}
Simplest way in java:
File input = new File("input/file");
File output = new File("output/file");
InputStream is = new FileInputStream(input); // can be any input stream, even url.open()
OutputStream os = new FileOutputStream(output);
byte[] buffer = new byte[4096];//
int read = 0;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
is.close();
os.close();
Try Apache Commons IO Utils.
FileUtils.copyFile(new File(inputPlayList),new File(outputPlayList));
Here it is, but I don't understand the meaning of the numberOfminutes argument, what is it for? I've changed implementation to return calculated number of minutes from the function.
import java.io.*;
public class Main {
public static void main(String[] args) {
System.out.println(copy("D:\\1.txt", "D:\\2.txt", 0)); //returns the calculated number of minutes
}
public static int copy(String inputPlayList, String outputPlayList, int numberOfMinutes) {
String start1 = "#EXTINF:";
String afterNum = ";";
try {
BufferedReader br = new BufferedReader(new FileReader(new File(inputPlayList)));
PrintWriter out = new PrintWriter(new FileWriter(outputPlayList));
String s;
while ((s = br.readLine()) != null) {
if (s.contains(start1)) {
String numberInString = s.substring(start1.length(), s.indexOf(afterNum));
numberOfMinutes += Integer.parseInt(numberInString);
}
out.println(s);
}
out.close();
} catch (IOException e) {
System.err.println("Exception" + e);
}
return numberOfMinutes;
}
}