A
A
ArtAVi2018-07-07 09:30:10
Java
ArtAVi, 2018-07-07 09:30:10

How to synchronize by file?

Please tell me how to make the streams synchronized according to the file "fileWithAnAdress.txt"

public class Main {

    public static void main(String[] args) {
        boolean delete1 = (new File("fileWithoutGarbage.txt")).delete();
        Thread thread = new Thread(new CreateFileService());
        thread.start();
        Thread thread1 = new Thread(new ReadFileService());
        thread1.start();
    }
}
public class CreateFileService implements Runnable {

    @Override
    public void run() {
       List<String> list = new ArrayList<>();
        list.add("'С:\\WebServers\\home\\testsite\\www\\myfile1.txt'");
        list.add("'С:\\WebServers\\home\\testsite\\www\\myfile2.txt'");
        list.add("'С:\\WebServers\\home\\testsite\\www\\myfile3.txt'");
        list.add("'С:\\WebServers\\home\\testsite\\www\\myfile4.txt'");
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("fileWithAnAdress.txt"));
            for (String s : list) {
                bw.write(s);
                bw.write(System.lineSeparator());
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class ReadFileService implements Runnable {

    @Override
    public void run() {
        List<String> lines = new ArrayList<>();
        List<String> newLines = new ArrayList<>();
        try {
            BufferedReader br = new BufferedReader(new FileReader("fileWithAnAdress.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
            System.out.println(lines);
            for (String s : lines) {
                String newString = s.substring(s.lastIndexOf('\\') + 1, s.lastIndexOf('.'));
                newLines.add(newString);
            }
            System.out.println(newLines);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("fileWithoutGarbage.txt"))) {
            for (String newLine : newLines) {
                bufferedWriter.write(newLine);
                bufferedWriter.write(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        File file = new File("fileWithoutGarbage.txt");
        System.out.println(file.length() + " byte");
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-07-07
@sergey-gornostaev Java Tag Curator

42

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question